Python将在具有重复值的单元格上添加条件

2024-04-26 05:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我上一个问题propagating values over non-unique (duplicate) cells in pandas的后续内容

我有一个数据帧:

import pandas as pd

df = pd.DataFrame({'First': ['Sam', 'Greg', 'Steve', 'Sam',
                             'Jill', 'Bill', 'Nod', 'Mallory', 'Ping', 'Lamar'],
                   'Last': ['Stevens', 'Hamcunning', 'Strange', 'Stevens',
                            'Vargas', 'Simon', 'Purple', 'Green', 'Simon', 'Simon'],
                   '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', '', 'Infected', '', '', '', '','', '', 'Infected'],
                   'Level': [10, 2, 7, 5, 2, 10, 10, 20, 1, 1],
                   })

假设这一次我想把状态值'infected'传播到同一地址内的每个人,并附加一个条件,比如如果他们在Last中有相同的值。 所以结果看起来像:

df2 = df1.copy(deep=True)
df2['Status'] = ['Infected', '', 'Infected', 'Infected', '', 'Infected', '', '', 'Infected', 'Infected']

如果我想让一个人被标记为感染,如果他在同一个地址,但不是同一级别?结果是:

df3 = df1.copy(deep=True)
df3['Status'] = ['Infected', '', 'Infected', '', '', 'Infected', '', '', '', 'Infected']

我该怎么做?这是一个groupby问题吗?你知道吗


Tags: pandasmain地址samstatusfakepdlast
1条回答
网友
1楼 · 发布于 2024-04-26 05:16:32

“同一地址”用“groupby”表示。你知道吗

import pandas as pd


df=pd.DataFrame({'First': [ 'Sam', 'Greg', 'Steve', 'Sam',
                 'Jill', 'Bill', 'Nod', 'Mallory', 'Ping', 'Lamar'],
                 'Last': [ 'Stevens', 'Hamcunning', 'Strange', 'Stevens',
                 'Vargas', 'Simon', 'Purple', 'Green', 'Simon', 'Simon'],
                 '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','','Infected','','','','','','','Infected'],
                 'Level': [10,2,7,5,2,10,10,20,1,1],
                 })

df2_index = df.groupby(['Address', 'Last']).filter(lambda x: (x['Status'] == 'Infected').any()).index
df2 = df.copy()
df2.loc[df2_index, 'Status'] = 'Infected'

df3_status = df.groupby('Address', as_index=False, group_keys=False).apply(lambda x: pd.Series(list('Infected' if (row['Status'] == 'Infected') or ((x['Status'] == 'Infected') & (x['Level'] != row['Level'])).any() else '' for _, row in x.iterrows()), index=x.index))
df3 = df.copy()
df3['Status'] = df3_status

相关问题 更多 >

    热门问题