[英]Merging and transforming two pandas dataframes
I have two pandas data frames: 我有两个pandas数据帧:
One in the format: 一种格式:
type sum date
x1 12 01/01/12
x2 10 01/01/12
x3 8 01/01/12
x1 13 02/01/12
x2 12 02/01/12
x3 55 02/01/12
x1 11 03/01/12
x2 10 03/01/12
x3 8 03/01/12
and another in the format 另一种格式
total date
122 01/01/12
133 02/01/12
144 03/01/12
What is the simplest way to combine these to so i could get the following output: 将这些组合起来的最简单方法是什么,以便我可以获得以下输出:
date x1 x2 x3 total
01/01/12 12 10 8 122
02/01/12 13 12 55 133
03/01/12 11 10 8 144
I have tried a lot of functions that are getting very messy, very quickly and do not seem to work. 我已经尝试了很多功能,这些功能变得非常混乱,非常快,似乎无法正常工作。
Any help would be greatly appreciated. 任何帮助将不胜感激。
You can use pivot
with df1
, set_index
with df2
and then concat
them together. 您可以使用pivot
与df1
, set_index
与df2
,然后concat
在一起。 Last you can remove columns name
and reset_index
: 最后,您可以删除columns name
和reset_index
:
print df1.pivot(index='date', columns='type', values='sum')
type x1 x2 x3
date
2012-01-01 12 10 8
2012-02-01 13 12 55
2012-03-01 11 10 8
print df2.set_index('date')
total
date
2012-01-01 122
2012-02-01 133
2012-03-01 144
df = pd.concat([df1.pivot(index='date', columns='type', values='sum'),
df2.set_index('date')], axis=1)
df.columns.name = None
df = df.reset_index()
print df
date x1 x2 x3 total
0 2012-01-01 12 10 8 122
1 2012-02-01 13 12 55 133
2 2012-03-01 11 10 8 144
And maybe before you can convert columns date
to_datetime
of both DataFrames
: 也许在你可以转换两个DataFrames
date
to_datetime
DataFrames
:
df1['date'] = pd.to_datetime(df1['date'])
df2['date'] = pd.to_datetime(df2['date'])
print df1
type sum date
0 x1 12 2012-01-01
1 x2 10 2012-01-01
2 x3 8 2012-01-01
3 x1 13 2012-02-01
4 x2 12 2012-02-01
5 x3 55 2012-02-01
6 x1 11 2012-03-01
7 x2 10 2012-03-01
8 x3 8 2012-03-01
print df2
total date
0 122 2012-01-01
1 133 2012-02-01
2 144 2012-03-01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.