i.n*_*n.m 23 python types copy pandas
这个问题已被问过很多次了,它似乎对其他人NaN有用,但是,当我从不同的DataFrame中复制一个列时,我得到了值(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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我需要这样的 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
Run Code Online (Sandbox Code Playgroud)
我试过以下,
df2['date'] = df1['date']
df2['hour'] = df1['hour']
type(df1)
>> pandas.core.frame.DataFrame
type(df2)
>> pandas.core.frame.DataFrame
Run Code Online (Sandbox Code Playgroud)
我得到以下,
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
Run Code Online (Sandbox Code Playgroud)
为什么会这样?还有另一篇文章讨论merge,但我只需要复制它.任何帮助,将不胜感激.
cs9*_*s95 27
您的DataFrame的索引不一样,因此请先重置它们.
# Setup
A = pd.DataFrame(index=['a', 'b', 'c'])
B = pd.DataFrame(index=['b', 'c', 'd', 'f'])
C = pd.DataFrame(index=[1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
或者,如果它们的长度相同,则将一个索引指定给另一个:
# Example of alignable indexes - A & B (complete or partial overlap of indexes)
A.index B.index
a
b b (overlap)
c c (overlap)
d
f
Run Code Online (Sandbox Code Playgroud)
现在,组合DataFrames,
# Example of unalignable indexes - A & C (no overlap at all)
A.index C.index
a
b
c
1
2
3
Run Code Online (Sandbox Code Playgroud)
WeN*_*Ben 16
试试这个 ?
df2['date'] = df1['date'].values
df2['hour'] = df1['hour'].values
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36594 次 |
| 最近记录: |