隨着DataFrame.append
需要Series
或DataFrame
具有相同index
或相同columns names
爲df
:
df1 = pd.DataFrame([[2, 4, 1]], columns=('x', 'y', 'label'))
print (df1)
x y label
0 2 4 1
df = df.append([pd.Series([4, 4, 1], index = df.columns)], ignore_index=True)
df = df.append(df1, ignore_index=True)
#your solution
df.loc[len(df)] = [4, 4, 1]
print (df)
x y label
0 4.0 4.0 1.0
1 2.0 4.0 1.0
2 4.0 4.0 1.0
#dont align because default columns names
df = df.append([[4, 4, 1]])
print (df)
x y label 0 1 2
0 NaN NaN NaN 4.0 4.0 1.0
但是,如果默認列名:
df = pd.DataFrame(columns=range(3))
print (df)
Empty DataFrame
Columns: [0, 1, 2]
Index: []
df = df.append([[4, 4, 1]])
print (df)
0 1 2
0 4.0 4.0 1.0
你是什麼意思「它不是很乾淨」。 –
說「添加行」比說「loc [len(df)]」更容易理解。 –