python - 在 pandas 中的非唯一(重复)单元格上传播值

标签 python pandas group-by

我有以下数据框

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/

相关文章:

python - 如何在 Tensorflow 中实现逐元素一维插值?

python - 使用 xlsxwriter 遍历工作表查看索引

python - 根据分组依据中的值数量来透视数据,而不是完整的透视

python - 2 groupby 在同一个数据框中,可能吗?

python - 使用 sklearn RandomForestRegressor 时我的数据帧的 x 值是多少?

python - 从连接到 QML 的 PyQt5 打开文件对话框

python - 按对象属性对对象字典进行分组

MySQL 按组对记录进行编号 - 我遇到错误了吗?

mysql - 获取 'COUNT'/'GROUP BY' MySQL 查询的空结果

tsql - 如何编写 T-SQL 查询来为每个客户端选择前 1 条记录?