我有一个数据框架:

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()函数,但找不到正确的方法。

如何添加/插入系列数据帧?


当前回答

给出熊猫数据框架的数据结构是一个序列列表(每个序列为一列),方便在任意位置插入一列。 我想到的一个办法是先转置数据帧,插入一列,再转置回来。你可能还需要重命名索引(行名),就像这样:

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

df = pd.DataFrame([list(s1), list(s2)],  columns =  ["A", "B", "C"])
df = df.transpose()
df.insert(0, 2, [2,3,4])
df = df.transpose()
df.index = [i for i in range(3)]
df

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

其他回答

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

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

要在任意位置插入新行,可以指定行位置: Row_pos = -1用于在顶部插入 或者row_pos = 0.5用于在第0行和第1行之间插入。

row_pos = -1
insert_row = [2,3,4]

df.loc[row_pos] = insert_row
df = df.sort_index()
df = df.reset_index(drop = True)

row_pos = -1

The outcome is:

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

row_pos = 0.5

The outcome is:

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

这看起来可能过于简单,但令人难以置信的是,一个简单的插入新行函数没有内置。我读了很多关于追加一个新的df到原来的,但我想知道这是否会更快。

df.loc[0] = [row1data, blah...]
i = len(df) + 1
df.loc[i] = [row2data, blah...]

只需将row赋值给一个特定的索引,使用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文档索引:放大设置。

我突然想到,也许T属性是一个有效的选择。转置,可以避开误导人的df。Loc[-1] =[2,3,4],就像@flow2k提到的那样,它适用于更通用的情况,比如你想在任意行之前插入[2,3,4],这是concat(),append()难以实现的。没有必要为定义和调试函数而费心。

a = df.T
a.insert(0,'anyName',value=[2,3,4])
# just give insert() any column name you want, we'll rename it.
a.rename(columns=dict(zip(a.columns,[i for i in range(a.shape[1])])),inplace=True)
# set inplace to a Boolean as you need.
df=a.T
df

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

我想这可以部分解释@MattCochrane抱怨为什么pandas没有像insert()那样插入一行的方法。

按照下面的例子做:

A_row = pd。系列([1,2])

Df = pd。DataFrame([[3,4], [5,6]])

row_df = pd.DataFrame([a_row])

Df = pd。concat([row_df, df], ignore_index=True)

结果是:

   0  1
0  1  2
1  3  4
2  5  6