import pandas as pd
data = {‘A’: [1, 2, 3], ‘B’: [4, 5, 6]}
df = pd.DataFrame(data)
new_row1 = {‘A’: 7, ‘B’: 8}
df = df.append(new_row, ignore_index=True)
print(df)
输出:
A B
0 1 4
1 2 5
2 3 6
3 7 8
append方法比较灵活,它还支持添加多行:
import pandas as pd
data = {‘A’: [1, 2, 3], ‘B’: [4, 5, 6]}
df = pd.DataFrame(data)
new_row1 = {‘A’: 7, ‘B’: 8}
new_row2 = {‘A’: 9, ‘B’: 10}
df = df.append([new_row1, new_row2], ignore_index=True)
print(df)
输出:
A B
0 1 4
1 2 5
2 3 6
3 7 8
4 9 10
使用 loc 和索引操作符 [] 追加新行:
import pandas as pd
data = {‘A’: [1, 2, 3], ‘B’: [4, 5, 6]}
df = pd.DataFrame(data)
new_row = {‘A’: 7, ‘B’: 8}
df.loc[len(df)] = new_row
print(df)
输出:
A B
0 1 4
1 2 5
2 3 6
3 7 8
将新行作为列表添加到 DataFrame:
import pandas as pd
data = {‘A’: [1, 2, 3], ‘B’: [4, 5, 6]}
df = pd.DataFrame(data)
new_row = [7, 8]
df.loc[len(df)] = new_row
print(df)
输出:
A B
0 1 4
1 2 5
2 3 6
3 7 8