我有一個包含多個字符串列的 Pandas 數據框。我現在想根據允許的子字符串列表檢查某個列,然后得到一個帶有結果的新子集。substr = ['A', 'C', 'D']df = pd.read_excel('output.xlsx')df = df.dropna()# now filter all rows where the string in the 2nd column doesn't contain one of the substrings我發現的唯一方法是創建相應列的列表,然后進行列表理解,但隨后我松開了其他列。我可以使用列表理解作為 eg 的一部分df.str.contains()嗎?year type value price2000 ty-A 500 100002002 ty-Q 200 846002003 ty-R 500 560002003 ty-B 500 180002006 ty-C 500 125002012 ty-A 500 650002018 ty-F 500 860002019 ty-D 500 51900預期輸出:year type value price2000 ty-A 500 100002006 ty-C 500 125002012 ty-A 500 650002019 ty-D 500 51900
2 回答

犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
你可以使用pandas.Series.isin
>>> df.loc[df['type'].isin(substr)]
year type value price
0 2000 A 500 10000
4 2006 C 500 12500
5 2012 A 500 65000
7 2019 D 500 51900

FFIVE
TA貢獻1797條經驗 獲得超6個贊
你可以使用pandas.DataFrame.any或pandas.DataFrame.all
如果你想要所有實例匹配的地方
df.loc[df['type'].apply(lambda x: all( word in x for word in substr)
或者如果你想要任何來自 substr
df.loc[df['type'].apply(lambda x: any( word in x for word in substr)
如果您打印或返回 df 過濾列表,則應該這樣做。
添加回答
舉報
0/150
提交
取消