将行追加到 Pandas DataFrame 添加 0 列

2024-04-28

我正在创建一个 Pandas DataFrame 来存储数据。不幸的是,我无法提前知道我将拥有的数据行数。所以我的方法如下。

首先,我声明一个空的 DataFrame。

df = DataFrame(columns=['col1', 'col2'])

然后,我附加一行缺失值。

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

最后,我可以一次将一个单元格的值插入到该 DataFrame 中。 (为什么我必须一次只做一个单元格这是一个很长的故事。)

df['col1'][0] = 3.28

这种方法工作得很好,除了附加语句向我的数据帧插入一个附加列之外。在该过程结束时,我键入时看到的输出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

关于造成此问题的任何想法0列出现在我的数据框中?


追加尝试将一列追加到您的数据框中。它尝试附加的列未命名,并且其中有两个 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将行追加到 Pandas DataFrame 添加 0 列 的相关文章

随机推荐