向 DataFrame 追加新行

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(columns = ['A', 'B', 'C'])

In [3]: df
Out[3]: 
Empty DataFrame
Columns: [A, B, C]
Index: []

按單列值追加一行:

In [4]: df.loc[0, 'A'] = 1

In [5]: df
Out[5]: 
   A    B    C
0  1  NaN  NaN

給定一行,給定值列表:

In [6]: df.loc[1] = [2, 3, 4]

In [7]: df
Out[7]: 
   A    B    C
0  1  NaN  NaN
1  2    3    4

在給定字典的情況下附加一行:

In [8]: df.loc[2] = {'A': 3, 'C': 9, 'B': 9}

In [9]: df
Out[9]: 
   A    B    C
0  1  NaN  NaN
1  2    3    4
2  3    9    9

.loc []中的第一個輸入是索引。如果使用現有索引,則將覆蓋該行中的值:

In [17]: df.loc[1] = [5, 6, 7]

In [18]: df
Out[18]: 
   A    B    C
0  1  NaN  NaN
1  5    6    7
2  3    9    9

In [19]: df.loc[0, 'B'] = 8

In [20]: df
Out[20]: 
   A  B    C
0  1  8  NaN
1  5  6    7
2  3  9    9