假设我在python中有两个 Pandas 系列:
import pandas as pd
h = pd.Series(['g',4,2,1,1])
g = pd.Series([1,6,5,4,"abc"])
我可以只用h创建一个DataFrame,然后将g附加到它:
df = pd.DataFrame([h])
df1 = df.append(g, ignore_index=True)
我得到:
>>> df1
0 1 2 3 4
0 g 4 2 1 1
1 1 6 5 4 abc
但是现在假设我有一个空的DataFrame,我尝试将h附加到它:
df2 = pd.DataFrame([])
df3 = df2.append(h, ignore_index=True)
这是行不通的。我认为问题出在代码的倒数第二行。我需要以某种方式定义空白DataFrame以具有适当的列数。
顺便说一句,我尝试这样做的原因是,我正在使用request + BeautifulSoup从Internet上抓取文本,并且正在处理它,并试图一次将其写入DataFrame。
最佳答案
因此,如果您不将空列表传递给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]
两种构造方法之间的区别似乎在于索引
dtypes
的设置不同,列表为空时,它是Int64
,没有内容,则是object
:In [21]:
df = pd.DataFrame()
print(df.index.dtype)
df = pd.DataFrame([])
print(df.index.dtype)
object
int64
我不清楚上述原因为何会影响行为(我在这里猜测)。
更新
再次查看之后,我可以确认这对我来说是 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]
我正在使用python
0.13.1
运行pandas 1.8.1
和numpy 3.3.5.0
64位,但我认为问题是pandas,但我会同时升级pandas和numpy以确保安全,我不认为这是32位对64位python问题。关于python - Python- Pandas -将系列追加到空白DataFrame中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23974802/