向Pandas DataFrame添加行时增加了0列
我正在创建一个Pandas的DataFrame来存储数据。不过,我事先并不知道会有多少行数据。所以我采取了以下方法。
首先,我声明一个空的DataFrame。
df = DataFrame(columns=['col1', 'col2'])
然后,我添加了一行缺失值。
df = df.append([None] * 2, ignore_index=True)
最后,我可以一个一个单元格地往这个DataFrame里插入值。(为什么要一个一个单元格插入,这个原因比较复杂。)
df['col1'][0] = 3.28
这个方法运行得很好,唯一的问题是,添加的那一行会在我的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 个回答
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
4
这个“append”是在尝试把一列数据加到你的数据框(dataframe)里。它想加的这一列没有名字,而且里面有两个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