Python - pandas - 将系列追加到空白DataFrame中

bil*_*999 6 python matrix dataframe pandas

说我在python中有两个pandas系列:

import pandas as pd
h = pd.Series(['g',4,2,1,1])
g = pd.Series([1,6,5,4,"abc"])
Run Code Online (Sandbox Code Playgroud)

我可以用h创建一个DataFrame,然后将g附加到它:

df = pd.DataFrame([h])
df1 = df.append(g, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

我明白了:

>>> df1
   0  1  2  3    4
0  g  4  2  1    1
1  1  6  5  4  abc
Run Code Online (Sandbox Code Playgroud)

但现在假设我有一个空的DataFrame,我尝试将h追加到它:

df2 = pd.DataFrame([])
df3 = df2.append(h, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

这不起作用.我认为问题出现在倒数第二行的代码中.我需要以某种方式定义空白DataFrame以具有适当数量的列.

顺便说一句,我试图这样做的原因是我使用requests + BeautifulSoup从互联网上抓文本,我正在处理它并尝试一次将它写入一行DataFrame.

EdC*_*ica 8

因此,如果您没有将空列表传递给DataFrame构造函数,那么它可以工作:

In [16]:

df = pd.DataFrame()
h = pd.Series(['g',4,2,1,1])
df = df.append(h,ignore_index=True)
df
Out[16]:
   0  1  2  3  4
0  g  4  2  1  1

[1 rows x 5 columns]
Run Code Online (Sandbox Code Playgroud)

两个构造函数方法之间的区别似乎是索引dtypes设置不同,一个空列表它Int64没有任何东西它是object:

In [21]:

df = pd.DataFrame()
print(df.index.dtype)
df = pd.DataFrame([])
print(df.index.dtype)
object
int64
Run Code Online (Sandbox Code Playgroud)

我不清楚为什么上面应该影响行为(我在这里猜测).

UPDATE

在重新访问之后,我可以确认这在我看来是pandas版本中的一个错误,0.12.0因为您的原始代码工作正常:

In [13]:

import pandas as pd
df = pd.DataFrame([])
h = pd.Series(['g',4,2,1,1])
df.append(h,ignore_index=True)

Out[13]:
   0  1  2  3  4
0  g  4  2  1  1

[1 rows x 5 columns]
Run Code Online (Sandbox Code Playgroud)

我正在使用python 运行pandas 0.13.1和numpy 1.8.164位,3.3.5.0但我认为问题是pandas但是我会升级两个pandas和numpy以保证安全,我不认为这是32和64位python问题.