我有以下数据框
df = pd.DataFrame({'Name': ['Sally', 'Fred', 'Tim'],
'Random Text - Amish': [1,1,1],
'Text is Random - Matt': [1,0,1],
'More Random Text - Luke': [1,0,0],
'OMG this text is random - Phil': [0,0,1],
})
我正在寻找一个列表,并根据列表显示相关的列。例如,如果我提供了list = ['Amish', 'Luke']
,它将仅显示那些列。真实的数据框架非常大,因此我需要为其提供一个列表,而不是手动指定哪些列。
答案 0 :(得分:0)
这是一个解决方案:
l = ['Amish', 'Luke']
columns = [c for c in df.columns for word in l if word in c]
df[columns]
输出为:
Random Text - Amish More Random Text - Luke
0 1 1
1 1 0
2 1 0
答案 1 :(得分:0)
在str.endswith
上使用df.columns
例如:
df = pd.DataFrame({'Name': ['Sally', 'Fred', 'Tim'],
'Random Text - Amish': [1,1,1],
'Text is Random - Matt': [1,0,1],
'More Random Text - Luke': [1,0,0],
'OMG this text is random - Phil': [0,0,1],
})
lst = ('Amish', 'Luke')
ndf = df[[c for c in df.columns if c.endswith(lst)]]
print(ndf)
输出:
Random Text - Amish More Random Text - Luke
0 1 1
1 1 0
2 1 0