我有一个函数,可以用未排序的索引创建几个熊猫数据框。我想将这些数据框中的值添加到基于索引的另一个数据框中的现有列。

明白我的意思:

# original dataframe
df_original = pd.DataFrame({'a':range(8), 'b':range(8)})
df_original['c'] = np.nan

   a  b   c
0  0  0 NaN
1  1  1 NaN
2  2  2 NaN
3  3  3 NaN
4  4  4 NaN
5  5  5 NaN
6  6  6 NaN
7  7  7 NaN


我的函数用未排序的索引一一返回数据帧:

# first df that is returned
df1 = pd.DataFrame(index=range(1,8,2), data=range(4), columns=['c'])

   c
1  0
3  1
5  2
7  3

# second df that is returned
df2 = pd.DataFrame(index=range(0,8,2), data=range(4), columns=['c'])

   c
0  0
2  1
4  2
6  3


我想按索引将这两个数据帧中的c列添加到原始数据帧的c列中的c列中,所以我最终得到:

# original dataframe in the end
    a   b   c
0   0   0   0
1   1   1   0
2   2   2   1
3   3   3   1
4   4   4   2
5   5   5   2
6   6   6   3
7   7   7   3


我怎样才能有效地做到这一点?我真正的原始数据帧包含大约10万行,并且每次调用该函数时都会返回大约100个值。最后,c列中将没有np.nan

我当前在函数末尾循环每个新数据框,并使用df_original.set_value()更改原始数据框中的值。肯定有更好的办法?

我也在考虑对所有新数据框进行df_temp = pd.concat((df1, df2...), axis=0),然后以pd.concat((df_original, df_temp), axis=1)完成。你会怎么做?

最佳答案

在我看来,双重concat解决方案很好。

另一种选择是使用join

df_temp = pd.concat([df1,df2])
df = df_original.join(df_temp)
print (df)
   a  b  c
0  0  0  0
1  1  1  0
2  2  2  1
3  3  3  1
4  4  4  2
5  5  5  2
6  6  6  3
7  7  7  3

关于python - 将具有未排序索引的多个 Pandas 数据框中的值插入到另一个数据框中的现有列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46973526/

10-09 19:50
查看更多