python - 向 Pandas 数据框插入一行

我有一个数据框:

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/

相关文章:

python - 如何在 Tesseract 和 OpenCV 之间进行选择?

python - 有效地检查 Python/numpy/pandas 中的任意对象是否为 NaN?

python - 如何从具有透明背景的 matplotlib 导出绘图?

python - matplotlib 中的曲面图

python - 在系统范围内安装 pip 和 virtualenv 的官方 "preferred"

python - 管道子流程标准输出到变量

python - 断言 numpy.array 相等性的最佳方法?

python - sqlite3.ProgrammingError : You must not u

python - SQLAlchemy:如何过滤日期字段?

python - 在 TensorFlow 中使用预训练的词嵌入(word2vec 或 Glove)