熊猫 - 合并两个dataframes具有不同数量的行
问题描述:
的我有以下两个dataframes:熊猫 - 合并两个dataframes具有不同数量的行
DF:
value
period
2000-01-01 100
2000-04-01 200
2000-07-01 300
2000-10-01 400
2001-01-01 500
DF1:
value
period
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
这是所需的输出:
df:
value
period
2000-01-01 100
2000-04-01 200
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
我在df1和df2上都有set_index(['period'])
。在创建新列之后,我也尝试了几件事情,包括concat和where语句,但没有按预期工作。我的第一个数据框是主要的。第二种是更新。它应该替换第一个对应的值,并且同时添加新的记录(如果有的话)。
我该怎么做?
答
您可以使用combine_first
,此外,如果一些指标的dtype
是object
转换to_datetime
如果总是df1.index
是很好的工作在df.index
:
print (df.index.dtype)
object
print (df1.index.dtype)
object
df.index = pd.to_datetime(df.index)
df1.index = pd.to_datetime(df1.index)
df = df1.combine_first(df)
#if necessary int columns
#df = df1.combine_first(df).astype(int)
print (df)
value
period
2000-01-01 100.0
2000-04-01 200.0
2000-07-01 350.0
2000-10-01 450.0
2001-01-01 550.0
2001-04-01 600.0
2001-07-01 700.0
如果没有,那么是必要的过滤器通过intersection
第一:
df = df1.loc[df1.index.intersection(df.index)].combine_first(df)
numpy.setdiff1d
与另一种溶液和concat
df = pd.concat([df.loc[np.setdiff1d(df.index, df1.index)], df1])
print (df)
value
period
2000-01-01 100
2000-04-01 200
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
答
这就是你想要的吗?
In [151]: pd.concat([df1, df.loc[df.index.difference(df1.index)]]).sort_index()
Out[151]:
value
period
2000-01-01 100
2000-04-01 200
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
PS确保这两个指标是相同的D型的 - 这是更好地将其转换为datetime
D型,使用pd.to_datetime()
方法
答
另一种选择用append
和drop_duplicates
d1 = df1.append(df)
d1[~d1.index.duplicated()]
value
period
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
2000-01-01 100
2000-04-01 200
答
我用pd.concat()共同作用关闭数据帧,然后删除重复项以获得结果。
df_con = pd.concat([df, df1])
df_con.drop_duplicates(subset="period",keep="last",inplace=True)
print(df_con)
period value
0 2000-01-01 100
1 2000-04-01 200
0 2000-07-01 350
1 2000-10-01 450
2 2001-01-01 550
3 2001-04-01 600
4 2001-07-01 700
要设置“期间”早在刚刚设置的索引的索引,
print(df_con.set_index("period"))
value
period
2000-01-01 100
2000-04-01 200
2000-07-01 350
2000-10-01 450
2001-01-01 550
2001-04-01 600
2001-07-01 700
它看起来像一个简单的串连。你能否详细说明“没有预期的工作”? –
这是行不通的:'pd.concat([df,df1],axis = 0)' – sretko
@AlIvon随意投票接受的答案和任何其他您认为有用的答案。 – piRSquared