我有一个数据框架:

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

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


当前回答

我突然想到,也许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()那样插入一行的方法。

其他回答

我们可以使用numpy.insert。这具有灵活性的优点。您只需要指定要插入的索引。

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

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

pd.DataFrame(np.insert(df.values, 0, values=[2, 3, 4], axis=0))

    0   1   2
0   2   3   4
1   5   6   7
2   7   8   9

np.insert (df。Values, 0, Values =[2,3,4], axis=0), 0告诉函数要放置新值的位置/索引。

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

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

我把一个简短的函数放在一起,在插入一行时允许更多的灵活性:

def insert_row(idx, df, df_insert):
    dfA = df.iloc[:idx, ]
    dfB = df.iloc[idx:, ]

    df = dfA.append(df_insert).append(dfB).reset_index(drop = True)

    return df

可以进一步缩写为:

def insert_row(idx, df, df_insert):
    return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop = True)

然后你可以使用如下语句:

df = insert_row(2, df, df_new)

其中2是df中要插入df_new的索引位置。

在pandas DataFrame中添加一行非常简单:

创建一个常规的Python字典,其列名与你的Dataframe相同; 使用pandas.append()方法并传入字典的名称,其中.append()是DataFrame实例上的方法; 在字典名称后面添加ignore_index=True。

下面是在不排序和重置索引的情况下将一行插入pandas数据框架的最佳方法:

import pandas as pd

df = pd.DataFrame(columns=['a','b','c'])

def insert(df, row):
    insert_loc = df.index.max()

    if pd.isna(insert_loc):
        df.loc[0] = row
    else:
        df.loc[insert_loc + 1] = row

insert(df,[2,3,4])
insert(df,[8,9,0])
print(df)