亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據子字符串列表過濾 Pandas 數據框

根據子字符串列表過濾 Pandas 數據框

忽然笑 2022-05-19 14:11:16
我有一個包含多個字符串列的 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


查看完整回答
反對 回復 2022-05-19
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

你可以使用pandas.DataFrame.anypandas.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 過濾列表,則應該這樣做。


查看完整回答
反對 回復 2022-05-19
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號