我有一個大約的資料框。10,000 行和 10 列。我有一個字串,我想在資料框中搜索它,稱為“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
uj5u.com熱心網友回復:
如果你已經有了你的結果,你可以簡單地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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447958.html
上一篇:如何統一單位?
