1. 程式人生 > 其它 >向dataframe中新增行

向dataframe中新增行

向 dataframe 中新增行有兩種方法, iloc 和 loc

不管什麼方法,都要事先準備一個與原資料列的個數相同的list或者是Series,比如[1, 2, 3, 4]

# 先定義一個 DataFream
import pandas as pd
df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])

```
   0  1  2  3
0  1  2  3  4
1  5  6  7  8
```

1. iloc[]

用iloc向 dataframe 中新增行使用如下程式碼:

# 向第[2]行新增
df.iloc[2] = [9, 10, 11, 12]

會報錯 IndexError: iloc cannot enlarge its target object,原因是dataframe沒有第[2]行, 而 iloc 只能在原先有資料的行進行修改,不能插入新的行。

2.loc[]

使用loc向 dataframe 新增行

df.loc[2] = [9, 10, 11, 12]
print(df)

# output

0	1	2	3
0	1	2	3	4
1	5	6	7	8
2	9	10	11	12

# 成功插入了

# 輸出df的行index
df.index
Int64Index([0, 1, 2], dtype='int64')

在loc中向 dataframe 新增行的原理是,loc[2] 去找 index 為 2 的行,如果沒有則建立一個index為2的行,然後再執行 df.loc[2] = [9, 10, 11, 12]