将数据帧中的一系列合并为具有相同索引的行

时间:2018-02-02 16:35:20

标签: python pandas

我有一个数据框和一个系列。两者都有相同的索引。我想在数据框中添加系列值作为一行以及相同的索引条目。

我的数据框和系列是:

    enter code here
index                       test            num       %change

cos                       7% 20_DA      22          37.93
cos                       7% 5_MS       8           13.79
fla                       5% 60_DA      67          31.75
fla                       7% 20_DA      35          16.59
fla                       7% 5_MS       19          9.00
gol                       7% 20_DA      22          20.95
gol                       7% 5_MS       10          9.52
ill                       7% 20_DA      50          64.94
ill                       7% 5_MS       29          37.66
lag                       7% 20_DA      21          46.67
lag                       7% 5_MS       7           15.56
lag                       5% 60_DA      18          28.12
lag                       7% 20_DA      14          21.88
lag                       7% 5_MS       6           9.38
le                        5% 60_DA      66          24.81
le                        7% 20_DA      67          25.19
le                        7% 5_MS       34          12.78
li                        7% 20_DA      59          70.24
li                        7% 5_MS       23          27.38
po                        5% 60_DA      32          12.65
po                        7% 20_DA      38          15.02
po                        7% 5_MS       23          9.09

和系列是

index       %change
cos         62.07
fla         68.25
gol         79.05
ill         35.06
lag         53.33
le          75.19
li          29.76
po          87.35

我的输出应该是

index                       test            num       %change

cos                       7% 20_DA         22           37.93
cos                       7% 5_MS          8            13.79
cos                         Nan             Nan         62.07

请建议一个方法。如果标题没有表明数据的相同意图,请告诉我。

1 个答案:

答案 0 :(得分:1)

假设您的系列名为series,而您的数据框名为df,则解决方案为:

pd.merge(df, pd.DataFrame(series), left_index=True, right_index=True)

编辑:

在仔细观察您想要的输出时,您可能正在寻找更类似的内容:

new_df = pd.concat((data, series), axis=0)
new_df['%change'][len(df):] = new_df[new_df.columns.values[-1]][len(df):]
new_df.drop(new_df.columns.values[-1], axis=1, inplace=True)

这将为您提供作为新行添加到'%change'列的系列的值。

相关问题