如果列名以某个字符串结尾,请删除数据帧列,Python3.6

2024-10-01 09:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下列的数据帧:

SectorName', 'Sector', 'ItemName', 'Item', 'Counterpart SectorName', 'Counterpart Sector', 'Stocks and TransactionsName', 'Stocks and Transactions', 'Units', 'Scale', 'Frequency', 'Date', 'Value'

如何从df中删除列,其中列名以Name结尾。在


Tags: and数据datevalueitemtransactionsunitsscale
1条回答
网友
1楼 · 发布于 2024-10-01 09:31:26

对于需要用^{}^{}删除的列,可以通过反转(~)布尔掩码进行筛选,同时使用^{}和{}进行字符串匹配:

cols = ['SectorName', 'Name Sector', 'ItemName', 'Item', 'Counterpart SectorName']
df = pd.DataFrame([range(5)], columns = cols)
print (df)
   SectorName  Name Sector  ItemName  Item  Counterpart SectorName
0           0            1         2     3                       4

print (~df.columns.str.endswith('Name'))
[False  True False  True False]

df1 = df.loc[:, ~df.columns.str.endswith('Name')]

^{pr2}$

或先筛选列名称:

print (df.columns[~df.columns.str.endswith('Name')])
Index(['Sector', 'Item'], dtype='object')

df1 = df[df.columns[~df.columns.str.endswith('Name')]]

print (df1)
   Name Sector  Item
0            1     3

相关问题 更多 >