使用 Pandas 将索引列添加到 DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9762935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add indexed column to DataFrame with pandas
提问by saroele
I'm a beginning pandas user, and after studying the documentation I still can't find a straightforward way to do the following.
我是 Pandas 的初级用户,在研究了文档后,我仍然找不到执行以下操作的简单方法。
I have a DataFrame with a pandas.DateRange index, and I want to add a column with values for part of the same DateRange.
我有一个带有 pandas.DateRange 索引的 DataFrame,我想添加一个列,其中包含同一 DateRange 的一部分的值。
Suppose I have
假设我有
df
A B
2010-01-01 00:00:00 0.340717 0.702432
2010-01-01 01:00:00 0.649970 0.411799
2010-01-01 02:00:00 0.932367 0.108047
2010-01-01 03:00:00 0.051942 0.526318
2010-01-01 04:00:00 0.518301 0.057809
2010-01-01 05:00:00 0.779988 0.756221
2010-01-01 06:00:00 0.597444 0.312495
and
和
df2
C
2010-01-01 03:00:00 5
2010-01-01 04:00:00 5
2010-01-01 05:00:00 5
How can I obtain something like this:
我怎样才能获得这样的东西:
A B C
2010-01-01 00:00:00 0.340717 0.702432 nan
2010-01-01 01:00:00 0.649970 0.411799 nan
2010-01-01 02:00:00 0.932367 0.108047 nan
2010-01-01 03:00:00 0.051942 0.526318 5
2010-01-01 04:00:00 0.518301 0.057809 5
2010-01-01 05:00:00 0.779988 0.756221 5
2010-01-01 06:00:00 0.597444 0.312495 nan
回答by Wes McKinney
回答by fantabolous
df['C'] = df2['C']should also work in this case.
df['C'] = df2['C']在这种情况下也应该工作。

