我在 pandas 中有两张桌子。其中大约有 10,000 多行,如下所示:
Table 1
col_1 date state ratio [50 more cols]
A 10/12 NY .5
A 12/05 MA NaN
.........
我有另一个大约 10 行的表,如下所示:
Table 2
date state ratio
12/05 MA .9
12/03 MA .8
............
我需要根据表 2 中的日期和状态值设置表 1 中的比率。理想的解决方案是合并日期和状态,但这会创建两列:ratio_x 和ratio_y
我需要一种方法将表 1 中的比率设置为表 2 中的相应比率,其中日期和状态都匹配。表1中的比率可以被覆盖。
如果可以通过合并正确完成此操作,那么这也是可行的。
Edit:您可以将表 2 视为映射到特定状态值(因此表 2 中的所有状态在此示例中均为 MA)
您需要选择哪个ratio
优先考虑的价值。假设您希望表 2 中的比率优先:
# join in ratio from the other table
table1 = table1.join(table2.set_index(["date", "state"])["ratio"].to_frame("ratio2"), on=["date", "state"])
# take ratio2 first, then the existing ratio value if ratio2 is null
table1["ratio"] = table1["ratio2"].fillna(table1["ratio"])
# delete the ratio2 column
del table1["ratio2"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)