此question已被多次询问,但似乎适用于其他人,但是,当我从其他DataFrame复制列时,我获得了NaN
个值df1
和df2
长度相同)。
df1
date hour var1
a 2017-05-01 00:00:00 456585
b 2017-05-01 01:00:00 899875
c 2017-05-01 02:00:00 569566
d 2017-05-01 03:00:00 458756
e 2017-05-01 04:00:00 231458
f 2017-05-01 05:00:00 986545
df2
MyVar1 MyVar2
0 6169.719338 3688.045368
1 5861.148007 3152.238704
2 5797.053347 2700.469871
3 5779.102340 2730.471948
4 6708.219647 3181.298291
5 8550.380343 3793.580394
我需要在df2
MyVar1 MyVar2 date hour
0 6169.719338 3688.045368 2017-05-01 00:00:00
1 5861.148007 3152.238704 2017-05-01 01:00:00
2 5797.053347 2700.469871 2017-05-01 02:00:00
3 5779.102340 2730.471948 2017-05-01 03:00:00
4 6708.219647 3181.298291 2017-05-01 04:00:00
5 8550.380343 3793.580394 2017-05-01 05:00:00
我尝试了以下内容,
df2['date'] = df1['date']
df2['hour'] = df1['hour']
type(df1)
>> pandas.core.frame.DataFrame
type(df2)
>> pandas.core.frame.DataFrame
我得到以下内容,
MyVar1 MyVar2 date hour
0 6169.719338 3688.045368 NaN NaN
1 5861.148007 3152.238704 NaN NaN
2 5797.053347 2700.469871 NaN NaN
为什么会这样?还有另一个post讨论了merge
,但我只需要复制它。任何帮助,将不胜感激。
答案 0 :(得分:16)
您的DataFrame索引不一样,因此请先重置它们。
df1, df2 = [d.reset_index(drop=True) for d in (df1, df2)]
或者,如果它们的长度相同,则将索引指定为另一个:
df1.index = df2.index
现在,合并DataFrames,
# pd.concat([df2, df1[['date', 'hour']]], axis=1)
df2.join(df1[['date', 'hour']])
MyVar1 MyVar2 date hour
0 6169.719338 3688.045368 2017-05-01 00:00:00
1 5861.148007 3152.238704 2017-05-01 01:00:00
2 5797.053347 2700.469871 2017-05-01 02:00:00
3 5779.102340 2730.471948 2017-05-01 03:00:00
4 6708.219647 3181.298291 2017-05-01 04:00:00
5 8550.380343 3793.580394 2017-05-01 05:00:00
答案 1 :(得分:11)
试试这个?
df2['date'] = df1['date'].values
df2['hour'] = df1['hour'].values