pandas 如果列名以某个字符串结尾,则删除数据框列,Python 3.6
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46346196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete data frame column if column name ends with some string, Python 3.6
提问by SPy
I have a dataframe with below columns:
我有一个包含以下列的数据框:
SectorName', 'Sector', 'ItemName', 'Item', 'Counterpart SectorName', 'Counterpart Sector', 'Stocks and TransactionsName', 'Stocks and Transactions', 'Units', 'Scale', 'Frequency', 'Date', 'Value'
How to delete column from dfwhere column name ends with Name.
如何从df列名以Name.
回答by jezrael
You can filter by inverting (~) boolean mask for columns which notneed delete with locand str.endswith, also working str.containswith $for match end of string:
您可以通过反相(〜)布尔掩码的列过滤不是需要与删除loc和str.endswith,也正在str.contains与$字符串匹配结束:
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')]
df1 = df.loc[:, ~df.columns.str.contains('Name$')]
Or filter columns names first:
或者先过滤列名:
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

