我试图仅删除列“ A”的第一次或最后一次出现。我怎么做? 下面的MWE会删除A的两列。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCA'))
print (df)
df.drop(df.columns[0], axis=1, inplace=True)
print (df)
答案 0 :(得分:3)
想法是为匹配项attachIpToWorkerNodes:
install:
envName: ${settings.envName}
jps:
type: update
name: Attach IP To Worker Nodes
onInstall: jelastic.env.binder.AttachExtIp [nodes.cp.join(id,)]
和重复项创建掩码-第一个或最后一个值,并用boolean indexing
用DataFrame.loc
过滤:
A
但是如果只需要第一个重复的列:
np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,size=(5, 4)), columns=list('ABCA'))
print (df)
A B C A
0 66 92 98 17
1 83 57 86 97
2 96 47 73 32
3 46 96 25 83
4 78 36 96 80
m1 = df.columns == 'A'
m2 = df.columns.duplicated()
m3 = df.columns.duplicated(keep='last')
df1 = df.loc[:, (m1 & m2) | ~m1]
print (df1)
B C A
0 92 98 17
1 57 86 97
2 47 73 32
3 96 25 83
4 36 96 80
df2 = df.loc[:, (m1 & m3) | ~m1]
print (df2)
A B C
0 66 92 98
1 83 57 86
2 96 47 73
3 46 96 25
4 78 36 96