How to remove duplicate column data based on column name in pandas

Suppose I have a table as shown below

    A   B   C   B
0   0   1   2   3
1   4   5   6   7

I would like to delete column B. I tried using drop_duplicate, but it seems that it only works based on duplicate data, not the header. Hope anyone knows how to do this.

thank

+10
source share
2 answers

Use with or and : Index.duplicatedlociloc boolean indexing

print (~df.columns.duplicated())
[ True  True  True False]

df = df.loc[:, ~df.columns.duplicated()]
print (df)
   A  B  C
0  0  1  2
1  4  5  6

df = df.iloc[:, ~df.columns.duplicated()]
print (df)
   A  B  C
0  0  1  2
1  4  5  6

Dates :

np.random.seed(123)
cols = ['A','B','C','B']
#[1000 rows x 30 columns]
df = pd.DataFrame(np.random.randint(10, size=(1000,30)),columns = np.random.choice(cols, 30))
print (df)

In [115]: %timeit (df.groupby(level=0, axis=1).first())
1000 loops, best of 3: 1.48 ms per loop

In [116]: %timeit (df.groupby(level=0, axis=1).mean())
1000 loops, best of 3: 1.58 ms per loop

In [117]: %timeit (df.iloc[:, ~df.columns.duplicated()])
1000 loops, best of 3: 338 Β΅s per loop

In [118]: %timeit (df.loc[:, ~df.columns.duplicated()])
1000 loops, best of 3: 346 Β΅s per loop

enter image description here

enter image description here

+22
source

groupby
axis=1 level=0, , . first , .

df.groupby(level=0, axis=1).first()

   A  B  C
0  0  1  2
1  4  5  6

last

df.groupby(level=0, axis=1).last()

   A  B  C
0  0  3  2
1  4  7  6

mean

df.groupby(level=0, axis=1).mean()

   A  B  C
0  0  2  2
1  4  6  6
+4

Source: https://habr.com/ru/post/1679323/


All Articles