熊猫,concat系列到DF作为行

Dic*_*man 9 python concat series pandas

我试图将一个系列添加到一个空的DataFrame中,但无法在Doc或其他问题中找到答案.由于您可以按行或按列附加两个DataFrame,因此系列中似乎必须缺少"轴标记".任何人都可以解释为什么这不起作用?

import Pandas as pd
df1 = pd.DataFrame()
s1 = pd.Series(['a',5,6])
df1 = pd.concat([df1,s1],axis = 1)
#go run some process return s2, s3, sn ...
s2 = pd.Series(['b',8,9])
df1 = pd.concat([df1,s2],axis = 1)
s3 = pd.Series(['c',10,11])
df1 = pd.concat([df1,s3],axis = 1)
Run Code Online (Sandbox Code Playgroud)

如果我上面的例子是一些误导,或许使用文档中的示例会有所帮助.

引用:将行附加到DataFrame.
虽然效率不高(因为必须创建一个新对象),但您可以通过将一个Series或dict传递给append来向DataFrame追加一行,这将返回一个新的DataFrame,如上所述.结束报价.

来自文档的示例附加"S",它是来自DataFrame的一行,"S1"是一个系列,并且尝试追加"S1"会产生错误.我的问题是为什么会附加"S1不起作用?问题背后的假设是DataFrame必须编码或包含两个轴的轴信息,其中一个系列必须只包含一个轴的信息.

df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
s = df.xs(3); #third row of DataFrame
s1 = pd.Series([np.random.randn(4)]); #new Series of equal len
df= df.append(s, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

结果

   0  1

0  a  b

1  5  8

2  6  9
Run Code Online (Sandbox Code Playgroud)

期望

   0  1 2

0  a  5 6

1  b  8 9
Run Code Online (Sandbox Code Playgroud)

Tom*_*ger 11

你很亲密,只是改变了结果 concat

In [14]: s1
Out[14]: 
0    a
1    5
2    6
dtype: object

In [15]: s2
Out[15]: 
0    b
1    8
2    9
dtype: object

In [16]: pd.concat([s1, s2], axis=1).T
Out[16]: 
   0  1  2
0  a  5  6
1  b  8  9

[2 rows x 3 columns]
Run Code Online (Sandbox Code Playgroud)

您也不需要创建空DataFrame.


jcd*_*ude 10

最好的方法是使用 DataFrame 从 Series 序列构造 DF,而不是使用 concat:

import pandas as pd
s1 = pd.Series(['a',5,6])
s2 = pd.Series(['b',8,9])
pd.DataFrame([s1, s2])
Run Code Online (Sandbox Code Playgroud)

输出:

In [4]: pd.DataFrame([s1, s2])
Out[4]: 
   0  1  2
0  a  5  6
1  b  8  9
Run Code Online (Sandbox Code Playgroud)