我有一个数据框:
s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])
df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C"])
A B C
0 5 6 7
1 7 8 9
[2 rows x 3 columns]
我需要添加第一行 [2, 3, 4] 来获取:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
我尝试了 append()
和 concat()
函数,但找不到正确的方法。
如何向数据框添加/插入系列?
最佳答案
只需使用 loc
将行分配给特定索引:
df.loc[-1] = [2, 3, 4] # adding a row
df.index = df.index + 1 # shifting index
df = df.sort_index() # sorting by index
你会得到,如你所愿:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
参见 Pandas 文档 Indexing: Setting with enlargement .
https://stackoverflow.com/questions/24284342/