2024-10-01 09:31:26 发布
网友
我有一个包含以下列的数据帧:
SectorName', 'Sector', 'ItemName', 'Item', 'Counterpart SectorName', 'Counterpart Sector', 'Stocks and TransactionsName', 'Stocks and Transactions', 'Units', 'Scale', 'Frequency', 'Date', 'Value'
如何从df中删除列,其中列名以Name结尾。在
df
Name
对于不需要用^{}和^{}删除的列,可以通过反转(~)布尔掩码进行筛选,同时使用^{}和{}进行字符串匹配:
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')]
或先筛选列名称:
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
对于不需要用^{} 和^{} 删除的列,可以通过反转(~)布尔掩码进行筛选,同时使用^{} 和{}进行字符串匹配:
^{pr2}$
或先筛选列名称:
相关问题 更多 >
编程相关推荐