2017-02-08 32 views
1

我的問題是如何通過使用DataFrame的append()方法乾淨地向DataFrame附加一行?熊貓追加()行具體示例

根據docs,append()將參數設置爲「DataFrame或Series/dict-like對象或這些對象的列表」中的參數給出的描述,我覺得這樣的事情應該是可能的,但我無法找到正確的語法:

df = pd.DataFrame(columns=('x', 'y', 'label')) 
df.append([2, 4, 1]) # Does not work 

我能追加一排df.loc[len(df)] = [4, 4, 1]但這不是很乾淨。

+0

你是什麼意思「它不是很乾淨」。 –

+0

說「添加行」比說「loc [len(df)]」更容易理解。 –

回答

0

您可以執行以下操作,以及:

df.loc[-1] = [4, 4, 1] 

實在沒辦法比少。

1

隨着DataFrame.append需要SeriesDataFrame具有相同index或相同columns namesdf

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