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

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

Python - 在數據框行內的列表中搜索元素

Python - 在數據框行內的列表中搜索元素

收到一只叮咚 2022-01-05 10:22:00
我正在嘗試捕獲列表格式的數據框/熊貓中的元素。如果字符串存在,下面會捕獲整個列表,我如何僅按行捕獲特定字符串的元素而忽略其余部分?這是我嘗試過的...l1 = [1,2,3,4,5,6]l2 = ['hello world \n my world','world is a great place \n we live in it','planet earth',np.NaN,'\n save the water','']df = pd.DataFrame(list(zip(l1,l2)),            columns=['id','sentence'])df['sentence_split'] = df['sentence'].str.split('\n')print(df)這段代碼的結果:df[df.sentence_split.str.join(' ').str.contains('world', na=False)]  # does the trick but still not exactly what I am looking for. id  sentence                                  sentence_split1   hello world \n my world                   [hello world , my world]2   world is a great place \n we live in it   [world is a great place , we live in it]但尋找:id  sentence                                  sentence_split1   hello world \n my world                   hello world; my world2   world is a great place \n we live in it   world is a great place
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

您正在尋找在一系列列表中搜索字符串。一種方法是:


# Drop NaN rows

df = df.dropna(subset=["sentence_split"])

應用僅保留您要查找的列表中的元素的函數


# Apply this lamda function

df["sentence_split"] = df["sentence_split"].apply(lambda x: [i for i in x if "world" in i])


   id                                 sentence             sentence_split

0   1                  hello world \n my world  [hello world ,  my world]

1   2  world is a great place \n we live in it  [world is a great place ]

2   3                             planet earth                         []

4   5                        \n save the water                         []

5   6                                                                  []


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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