pandas 将数组添加到熊猫数据框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34932862/
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 array into pandas dataframe
提问by Filip Eriksson
I have a pandas dataframe called A with one column called "a":
我有一个名为 A 的 Pandas 数据框,其中有一列名为“a”:
- date a
- 2016-01-19 3
- 2016-01-20: 1
- 2016-01-21: 2
- 日期 a
- 2016-01-19 3
- 2016-01-20:1
- 2016-01-21:2
I have one array that looks like: [4,3,2]. I want to insert this array into the dataframe and give the new column the name b. How do I do that?
我有一个数组,看起来像:[4,3,2]。我想将此数组插入到数据框中,并将新列命名为 b。我怎么做?
Expected output:
预期输出:
- date a b
- 2016-01-19 3 4
- 2016-01-20: 1 3
- 2016-01-21: 2 2
- 日期ab
- 2016-01-19 3 4
- 2016-01-20: 1 3
- 2016-01-21: 2 2
回答by Anton Protopopov
As @mgc pointed out in the comment you could do df['b'] = l
:
正如@mgc 在评论中指出的,你可以这样做df['b'] = l
:
import pandas as pd
from io import StringIO
data="""
date a
2016-01-19 3
2016-01-20 1
2016-01-21 2
"""
df = pd.read_csv(StringIO(data), sep='\s+')
df = df.set_index('date')
df.index = pd.to_datetime(df.index)
print(df)
a
date
2016-01-19 3
2016-01-20 1
2016-01-21 2
l = [4,3,2]
df['b'] = l
print(df)
a b
date
2016-01-19 3 4
2016-01-20 1 3
2016-01-21 2 2