我有一个数据框架:

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

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


当前回答

下面是在不排序和重置索引的情况下将一行插入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)

其他回答

不知道你是如何调用concat(),但它应该工作,只要两个对象是相同的类型。也许问题是你需要将你的第二个向量转换为一个数据框架?使用df,你定义了以下工作为我:

df2 = pd.DataFrame([[2,3,4]], columns=['A','B','C'])
pd.concat([df2, df])

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

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

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

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数据框架的最佳方法:

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)

创建列名为空df:

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

插入新行:

df.loc[len(df.index)] = [2, 3, 4]
df.loc[len(df.index)] = [5, 6, 7]
df.loc[len(df.index)] = [7, 8, 9]