python - 从 pandas 中的分组分配值

标签 python pandas dataframe multiple-columns assign

我有一个无法解决的问题。让我们看看你是否能帮助我。

我有这个 df:

df = pd.DataFrame(np.random.randint(0,3,size=(7, 4)),columns=['ONE', 'TWO', 'NAMES', 'FOUR'],index = fechas)
df['NAMES'] = ['Peter','Jon',' Mary','Mary','Peter','Peter','Mary']

假设我想按列名称中的名称进行分组,完成此操作后,我想按照最近完成的组将列 1 的值分配给列 2,遵循我必须分配值的标准第 1 列中的元素按名称添加到第 4 列中第一个 0 的整个组

这就是我得到的

            ONE  TWO  NAMES  FOUR
1970-01-01    0    0  Peter     0
1970-01-02    2    1    Jon     0
1970-01-03    1    0   Mary     0
1970-01-04    1    1   Mary     0
1970-01-05    0    2  Peter     1
1970-01-06    2    2  Peter     0
1970-01-07    0    0   Mary     1

我需要这样的东西:

            ONE  TWO  NAMES  FOUR
1970-01-01    0    0  Peter     0
1970-01-02    2    1    Jon     0
1970-01-03    1    1   Mary     0
1970-01-04    1    1   Mary     0
1970-01-05    0    0  Peter     1
1970-01-06    2    0  Peter     0
1970-01-07    0    1   Mary     1

我希望这一切都能得到很好的解释。 谢谢

最佳答案

我认为您需要首先按 boolean indexing 进行过滤FOUR 列中包含 0 的所有行,然后是 drop_duplicates通过 NAMES 列并保留第一个值。然后转换为 dictNAMES 作为键,ONE 作为值和 map :

df = pd.DataFrame({
'ONE': [0, 2, 1, 1, 0, 2, 0], 
'TWO': [0, 1, 0, 1, 2, 2, 0], 
'NAMES': ['Peter', 'Jon', 'Mary', 'Mary', 'Peter', 'Peter', 'Mary'], 
'FOUR': [0, 0, 0, 0, 1, 0, 1]})
df = df[['ONE', 'TWO', 'NAMES', 'FOUR']]
print (df)
   ONE  TWO  NAMES  FOUR
0    0    0  Peter     0
1    2    1    Jon     0
2    1    0   Mary     0
3    1    1   Mary     0
4    0    2  Peter     1
5    2    2  Peter     0
6    0    0   Mary     1
print (df[df.FOUR == 0].drop_duplicates(['NAMES']))
   ONE  TWO  NAMES  FOUR
0    0    0  Peter     0
1    2    1    Jon     0
2    1    0   Mary     0

d = df[df.FOUR == 0].drop_duplicates(['NAMES']).set_index('NAMES')['ONE'].to_dict()
print (d)
{'Jon': 2, 'Mary': 1, 'Peter': 0}

df.TWO = df.NAMES.map(d)
print (df)
            ONE  TWO  NAMES  FOUR
1970-01-01    0    0  Peter     0
1970-01-02    2    2    Jon     0
1970-01-03    1    1   Mary     0
1970-01-04    1    1   Mary     0
1970-01-05    0    0  Peter     1
1970-01-06    2    0  Peter     0
1970-01-07    0    1   Mary     1

关于python - 从 pandas 中的分组分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931018/

相关文章:

python - 同一个单词出现 KeyError

python - 有没有办法遍历列表并返回以其内容命名的变量?

python - 值错误: could not convert string to float: 'FEE'

python - 如何使用 groupbys 成为更快的 Pandas

python - 转换 DataFrame 中的每个组

python - 导入错误: matplotlib requires pyparsing >= 1. 5.6

python - 这个安全需求怎么设计?

python - Django - 收到来自外部站点的流请求

python - 如何在特定条件下仅获取数据帧的第二个索引

python - 在数据帧上切换列和行