我正在嘗試洗掉廣泛資料集的所有行串列中的組織列中列出的美國。
我的 df 看起來像這樣:
| ID | 組織 |
|---|---|
| 1 | ['教育','健康','美國','facebook'] |
| 2 | ['健康','航空公司','WHO','美國'] |
...
我希望我的輸出看起來像這樣:
| ID | 組織 |
|---|---|
| 1 | ['教育','健康','facebook'] |
| 2 | ['健康','航空公司','WHO'] |
我試過的代碼:
df=df['organizations'].remove("United States")
給了我以下錯誤:
AttributeError: 'Series' object has no attribute 'remove'
uj5u.com熱心網友回復:
你需要在這里回圈,使用apply:
df['Organizations'].apply(lambda l: l.remove('United States'))
或串列理解:
df['Organizations'] = [[x for x in l if x != 'United States'] for l in df['Organizations']]
輸出:
ID Organizations
0 1 [education, health, facebook]
1 2 [health, Airlines, WHO]
請注意,如果您在所有串列中都沒有“美國”,第一個將失敗
處理 NaN
df['Organizations'] = [[x for x in l if x != 'United States']
if isinstance(l, list) else l
for l in df['Organizations']]
使用的輸入:
df = pd.DataFrame({'ID': [1, 2],
'Organizations': [['education', 'health', 'United States', 'facebook'],
['health', 'Airlines', 'WHO', 'United States']]})
uj5u.com熱心網友回復:
您還可以考慮:
(df.explode('Organizations')
.query('Organizations != "United States"').groupby('ID')
.agg(list).reset_index())
ID Organizations
0 1 [education, health, facebook]
1 2 [health, Airlines, WHO]
uj5u.com熱心網友回復:
另一種方法是爆炸,洗掉值,然后聚合回來groupby:
df['Organizations'] = df['Organizations'].explode()\
.loc[lambda x: x!='United States']]\
.groupby(level=0).agg(list)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/487284.html
上一篇:為什么在python2.7中使用subprocess.check_output(shell=True)會導致掛起?
