python - 根据条件将缺失的行从一个数据帧添加到另一个数据帧
问题描述
我的示例数据如下:
data1 = {'index': ['001', '001', '001', '002', '002', '003', '004','004'],
'type' : ['red', 'red', 'red', 'yellow', 'red', 'green', 'blue', 'blue'],
'class' : ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']}
df1 = pd.DataFrame (data1, columns = ['index', 'type', 'class'])
df1
index type class
0 001 red A
1 001 red A
2 001 red A
3 002 yellow A
4 002 red A
5 003 green A
6 004 blue A
7 004 blue A
data2 = {'index': ['001', '001', '002', '003', '004'],
'type' : ['red', 'red', 'yellow', 'green', 'blue'],
'class' : ['A', 'A', 'A', 'B', 'A'],
'outcome': ['in', 'in', 'out', 'in', 'out']}
df2 = pd.DataFrame (data2, columns = ['index', 'type', 'class', 'outcome'])
df2
index type class outcome
0 001 red A in
1 001 red A in
2 002 yellow A out
3 003 green B in
4 004 blue A out
在df1
, 在class = A
, 在df2
它可以是A
,B
或C
. 我想在df2
from中添加缺少的行df1
。df1
具有每个索引的类型计数。例如,如果 in df1
index001
出现 3 次,则意味着我也应该在df2
. 对于df1
不在 中的行df2
,列outcome
应等于 NaN。输出应该是:
index type class outcome
0 001 red A in
1 001 red A in
2 001 red A NaN
3 002 yellow A out
4 002 red A NaN
5 003 green A NaN
6 003 green B in
7 004 blue A out
8 004 blue A NaN
我尝试使用 pd.concat 和 pd.merge 但我不断收到重复或添加错误的行。有人知道如何做到这一点吗?
解决方案
用于唯一性的计数器值,因此可能在下一步中GroupBy.cumcount
使用外连接:DataFrame.merge
df1['group'] = df1.groupby(['index','type','class']).cumcount()
df2['group'] = df2.groupby(['index','type','class']).cumcount()
df = (df1.merge(df2, on=['index','type','class','group'], how='outer')
.sort_values(by=['index', 'class'])
.drop(columns='group'))
print (df)
index type class outcome
0 001 red A in
1 001 red A in
2 001 red A NaN
3 002 yellow A out
4 002 red A NaN
5 003 green A NaN
8 003 green B in
6 004 blue A out
7 004 blue A NaN
推荐阅读
- java - 机器可以在读取 volatile 变量之前获得其他变量的可见性吗?
- selenium - 从 Jenkins 运行脚本时出现“超时”和“无法定位元素”
- r - devtools::use_vignette("my_package") 给出错误
- google-cloud-platform - GCP 是否提供多区域 VM 实例?
- ssh - Jmeter分布式测试通过SSH连接被拒绝
- typescript - Typescript 不会将 undefined 推断为 array.prototype.find 的返回类型
- python - 有没有更短的方法来替换字符串中的单词?
- python-3.x - Python:如何在装饰器中找到包装的函数参数?
- java - 为 Tomcat 配置 SSL 的步骤是什么?
- c - C标准是否要求指针是(整数)数字?