[英]Find substring in pandas dataframe and save in new column
我有一個 dataframe 大約。 10,000 行和 10 列。 我有一個字符串,我想在 dataframe 中搜索它,稱為“atmosphere”。 該字符串連續只能找到一次。 我只想保留包含此字符串的單元格,但保留它們的全部內容,並將它們保存在新列中。 我已經找到了以下解決方案,但它只返回“True”(當單元格包含字符串時)或“False”(當它不包含字符串時)。:
df.apply(lambda col: col.str.contains('atmosphere', case=False), axis=1)
Output:
col_1 col_2 col_3 col_4 ...
1 True False False False
2 False True False False
3 True False False False
...
我怎樣才能從這個到這個?:
new_col
1 today**atmosphere**is
2 **atmosphere**humid
3 the**atmosphere**now
如果你已經有了你的結果,你可以簡單地stack
它:
df = pd.DataFrame({"a":["apple", "orange", "today atmosphere"],
"b":["pineapple", "atmosphere humid", "kiwi"],
"c":["the atmosphere now", "watermelon", "grapes"]})
a b c
0 apple pineapple the atmosphere now
1 orange atmosphere humid watermelon
2 today atmosphere kiwi grapes
print (df[df.apply(lambda col: col.str.contains('atmosphere', case=False), axis=1)].stack())
0 c the atmosphere now
1 b atmosphere humid
2 a today atmosphere
dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.