我有一个看起来像这样的数据框:
+------+------------+-------+--------------+
| name | date | value | replacement |
+------+------------+-------+--------------+
| A | 20/11/2016 | 10 | NaN |
| C | 20/11/2016 | 8 | [A,B] |
| B | 20/11/2016 | 12 | NaN |
| E | 25/12/2016 | 16 | NaN |
| F | 25/12/2016 | 18 | NaN |
| D | 25/12/2016 | 11 | [E,F] |
+------+------------+-------+--------------+
我想做的是:
对于在“替换”列中具有名称列表的每一行,我希望将其“值”平均分配给包含相同日期的那些替换项+的行。
对于前面的示例,输出将如下所示:
+------+------------+-------+------------------+
| name | date | value | additional value |
+------+------------+-------+------------------+
| A | 20/11/2016 | 10 | 4 |
| B | 20/11/2016 | 12 | 4 |
| A | 25/12/2016 | 16 | 5.5 |
| B | 25/12/2016 | 18 | 5.5 |
+------+------------+-------+------------------+
我设法找到一种方法来直接执行分布,而不用通过拆分这些行并按名称+日期分组来创建新列,但是1 /太慢了+ 2 /我确实需要创建该额外的列并且找不到这样做的方式。
最佳答案
想法是通过使用replacement
的Series.str.len
列表的长度创建一个新列,然后将DataFrame.explode
(熊猫0.25+)创建为标量。将列value
除以new
,将merge
除以原始,再用另一列名称添加原始列:
df1 = df.assign(new=df['replacement'].str.len()).explode('replacement')
df1['new'] = df1['value'].div(df1['new'])
df1 = df1[['name','date','value']].merge(df1[['replacement','date','new']],
left_on=['name','date'],
right_on=['replacement','date'])
df1['replacement'] = df1.pop('new')
print (df1)
name date value replacement
0 A 20/11/2016 10 4.0
1 B 20/11/2016 12 4.0
2 A 25/12/2016 16 5.5
3 B 25/12/2016 18 5.5
通过删除类似的解决方案,而是选择:
df1 = df.assign(new=df['replacement'].str.len()).explode('replacement')
df1['new'] = df1['value'].div(df1['new'])
df1 = df1.drop(['replacement','new'],1).merge(df1.drop(['name','value'],1),
left_on=['name','date'],
right_on=['replacement','date'])
df1['replacement'] = df1.pop('new')
print (df1)
name date value replacement
0 A 20/11/2016 10 4.0
1 B 20/11/2016 12 4.0
2 A 25/12/2016 16 5.5
3 B 25/12/2016 18 5.5
关于python - 将行分布在共享相同 key 的其他行上,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59630237/