我有以下数据框
import pandas as pd
df=pd.DataFrame({'Players': [ 'Sam', 'Greg', 'Steve', 'Sam',
'Jill', 'Bill', 'Nod', 'Mallory', 'Ping', 'Lamar'],
'Address': ['112 Fake St','13 Crest St','14 Main St','112 Fake St','2 Morningwood','7 Cotton Dr','14 Main St','20 Main St','7 Cotton Dr','7 Cotton Dr'],
'Status': ['Infected','','Dead','','','','','','','Infected'],
})
print(df)
我想将状态值“感染”传播给同一地址内的每个人。
这意味着,如果同一地址中有多个人,并且其中一人处于感染状态,那么每个人都将具有此状态。
所以结果看起来像这样:
df2=pd.DataFrame({'Players': [ 'Sam', 'Greg', 'Steve', 'Sam',
'Jill', 'Bill', 'Nod', 'Mallory', 'Ping', 'Lamar'],
'Address': ['112 Fake St','13 Crest St','14 Main St','112 Fake St','2 Morningwood','7 Cotton Dr','14 Main St','20 Main St','7 Cotton Dr','7 Cotton Dr'],
'Status': ['Infected','','Dead','Infected','','Infected','','','Infected','Infected'],
})
print(df2)
我该怎么做?到目前为止我尝试过这个:
df[df.duplicated("Address")]
但它只选择后面的重复项,而不是全部
最佳答案
这是一种方法:
In [19]:
infected = df[df['Status']=='Infected'].set_index('Address')
df.loc[df['Address'].isin(infected.index),'Status'] = df['Address'].map(infected['Status']).fillna('')
df
Out[19]:
Address Players Status
0 112 Fake St Sam Infected
1 13 Crest St Greg
2 14 Main St Steve Dead
3 112 Fake St Sam Infected
4 2 Morningwood Jill
5 7 Cotton Dr Bill Infected
6 14 Main St Nod
7 20 Main St Mallory
8 7 Cotton Dr Ping Infected
9 7 Cotton Dr Lamar Infected
因此,这首先构建了 df 的 View ,其中状态为“已感染”,然后我们将索引设置为地址,这将创建一个查找表,然后我们可以使用 map
查找地址。位于infected
索引中并返回状态。
我在这里使用 loc
仅选择受感染索引中的地址,而不影响其他行。
关于python - 在 pandas 中的非唯一(重复)单元格上传播值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30445883/