向 Pandas DataFrame 添加行会添加 0 列

3
我正在创建一个Pandas DataFrame来存储数据。不幸的是,我无法预先知道将要有多少行数据。因此,我的方法如下。
首先,我声明一个空的DataFrame。
df = DataFrame(columns=['col1', 'col2'])

然后,我添加了一行缺失值。

df = df.append([None] * 2, ignore_index=True)

最后,我可以一次插入一个单元格的值到这个DataFrame中。(为什么我必须这样做是一个漫长的故事。)
df['col1'][0] = 3.28

这种方法完全可行,但有一个例外,就是append语句会向我的DataFrame中插入一列额外的数据。在处理过程结束时,当我键入df时看到的输出结果如下(包含100行数据)。
<class 'pandas.core.frame.DataFrame'>
Data columns (total 2 columns):
0            0  non-null values
col1         100  non-null values
col2         100  non-null values

df.head() 看起来是这样的。

      0   col1   col2
0  None   3.28      1
1  None      1      0
2  None      1      0
3  None      1      0
4  None      1      1

您对于我DataFrame中出现0列的原因有何想法吗?

2个回答

4

append是尝试向您的数据帧添加一列。它尝试添加的列没有命名,并且其中有两个None/Nan元素,pandas将默认将其命名为列0。

为了成功地执行此操作,传入数据帧的列名必须与当前数据帧列名保持一致,否则将创建新列(默认情况下)。

#you need to explicitly name the columns of the incoming parameter in the append statement
df = DataFrame(columns=['col1', 'col2'])
print df.append(Series([None]*2, index=['col1','col2']), ignore_index=True)


#as an aside

df = DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
dfRowImproper = [1,2,3,4]
#dfRowProper = DataFrame(arange(4)+1,columns=['A','B','C','D']) #will not work!!! because arange returns a vector, whereas DataFrame expect a matrix/array#
dfRowProper = DataFrame([arange(4)+1],columns=['A','B','C','D']) #will work


print df.append(dfRowImproper) #will make the 0 named column with 4 additional rows defined on this column

print df.append(dfRowProper) #will work as you would like as the column names are consistent

print df.append(DataFrame(np.random.randn(1,4))) #will define four additional columns to the df with 4 additional rows


print df.append(Series(dfRow,index=['A','B','C','D']), ignore_index=True) #works as you want

1
您可以使用Series进行行插入:
df = pd.DataFrame(columns=['col1', 'col2'])
df = df.append(pd.Series([None]*2), ignore_index=True)
df["col1"][0] = 3.28

df 的样子如下:

   col1 col2
0  3.28  NaN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接