[英]How to update a df based in a list. Python
我有下一個 df:
import pandas as pd
data = [{'car' :'audi','id':'ab','year':2001,'wheel':4},
{'car' :'honda','id':'aa','year':2002,'wheel':15},
{'car' :'tesla','id':'aaa','year':2003,'wheel':5}]
keys=['a','aa','aaa','avaa','2ffa']
車 | ID | 年 | 地位 | 車輪 |
---|---|---|---|---|
奧迪 | ab | 2001年 | 好的 | 4個 |
本田 | 咩 | 2002年 | 好的 | 4個 |
特斯拉 | 啊啊 | 2003年 | 好的 | 4個 |
特斯拉 | 阿瓦 | 2023年 | 好的 | 4個 |
那么,讓我們想象下一種情況:密鑰列表中的 ID 有缺陷,因此,我必須在適當的情況下將“狀態”列更新為“有缺陷”而不是“正常”。
我怎樣才能做到這一點? 謝謝!
使用isin
結合boolean 索引:
df.loc[df['id'].isin(keys), 'Status'] = 'Defective'
更新df
:
car id year wheel Status
0 audi ab 2001 4 NaN
1 honda aa 2002 15 Defective
2 tesla aaa 2003 5 Defective
使用的輸入:
df = pd.DataFrame(data)
In [220]: data = [{'car' :'audi','id':'ab','year':2001,'wheel':4},
...: {'car' :'honda','id':'aa','year':2002,'wheel':15},
...: {'car' :'tesla','id':'aaa','year':2003,'wheel':5}]
...:
...: keys=['a','aa','aaa','avaa','2ffa']
...:
In [221]: df = pd.DataFrame(data)
In [222]: df
Out[222]:
car id year wheel
0 audi ab 2001 4
1 honda aa 2002 15
2 tesla aaa 2003 5
In [223]: df['status'] = "OK"
In [224]: df
Out[224]:
car id year wheel status
0 audi ab 2001 4 OK
1 honda aa 2002 15 OK
2 tesla aaa 2003 5 OK
In [225]: for k in keys:
...: df.loc[df.id==k, 'status'] = "Defective"
...:
In [226]: df
Out[226]:
car id year wheel status
0 audi ab 2001 4 OK
1 honda aa 2002 15 Defective
2 tesla aaa 2003 5 Defective
您可以將np.where
與isin
一起使用:
df['Status'] = np.where(df['id'].isin(keys), 'Defective', 'OK')
print(df)
# Output
car id year wheel Status
0 audi ab 2001 4 OK
1 honda aa 2002 15 Defective
2 tesla aaa 2003 5 Defective
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.