首页  >  文章  >  后端开发  >  如何使用 loc、移位索引和排序将行插入 Pandas Dataframe

如何使用 loc、移位索引和排序将行插入 Pandas Dataframe

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-23 06:37:02249浏览

How to Insert a Row into a Pandas Dataframe using loc, Shifting Index, and Sorting

将行插入 Pandas 数据框

使用 Pandas 数据框时,您可能会遇到需要在特定位置插入新行的情况。假设您有一个包含两个系列 s1 和 s2 的数据框,表示如下:

<code class="python">s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

df = pd.DataFrame([list(s1), list(s2)],  columns =  ["A", "B", "C"])

print(df)</code>
   A  B  C
0  5  6  7
1  7  8  9

[2 rows x 3 columns]

要添加值为 [2, 3, 4] 作为第一行的新行,请按照以下步骤操作步骤:

1.使用 loc:

<code class="python">df.loc[-1] = [2, 3, 4]  # adding a row</code>

2 将行分配给特定索引。将索引移动 1:

<code class="python">df.index = df.index + 1  # shifting index</code>

3。按索引排序:

<code class="python">df = df.sort_index()  # sorting by index</code>

执行这些步骤后,您将获得所需的输出:

    A  B  C
 0  2  3  4
 1  5  6  7
 2  7  8  9

如 Pandas 文档中关于索引:设置放大的说明,这种方法允许您通过扩大索引来向数据帧添加新行。 loc 函数允许您将值分配给特定索引,在本例中,-1 表示新行。移动索引并按索引排序可确保新行作为数据帧中的第一行插入。

以上是如何使用 loc、移位索引和排序将行插入 Pandas Dataframe的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn