Home > Blockchain >  Drop specific column and indexes in pandas DataFrame
Drop specific column and indexes in pandas DataFrame

Time:10-24

DataFrame:

   A   B   C
0  1   6  11
1  2   7  12
2  3   8  13
3  4   9  14
4  5  10  15

Is it possible to drop values from index 2 to 4 in column B? or replace it with NaN.

In this case, values: [8, 9, 10] should be removed.

I tried this: df.drop(columns=['B'], index=[8, 9, 10]), but then column B is removed.

CodePudding user response:

import pandas as pd

data = [
    ['A','B','C'],
    [1,6,11],
    [2,7,12],
    [3,8,13],
    [4,9,14],
    [5,10,15]
]

df = pd.DataFrame(data=data[1:], columns=data[0])
df['B'] = df['B'].shift(3)

>>>

   A   B    C
0  1   NaN  11
1  2   NaN  12
2  3   NaN  13
3  4   6.0  14
4  5   7.0  15

CodePudding user response:

Drop values does not make sense into DataFrame. You can set values to NaN instead and use .loc / .iloc to access index/columns:

>>> df
   A   B   C
a  1   6  11
b  2   7  12
c  3   8  13
d  4   9  14
e  5  10  15

# By name:
df.loc['c':'e', 'B'] = np.nan

# By number:
df.iloc[2:5, 2] = np.nan

Read carefully Indexing and selecting data

  • Related