【发布时间】:2017-10-27 11:01:08
【问题描述】:
我有一个函数可以创建几个带有未排序索引的 pandas 数据框。我想根据索引将这些数据框中的值添加到另一个数据框中的现有列中。
明白我的意思:
# 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
我怎样才能有效地做到这一点?我真正的原始数据框包含大约 100k 行,每次调用该函数都会返回大约 100 个值。最后c列中不会有np.nan。
我目前在函数末尾循环每个新数据帧,并使用df_original.set_value() 更改原始数据帧中的值。一定有更好的办法吗?
我也在考虑用df_temp = pd.concat((df1, df2...), axis=0) 处理所有新的数据帧,然后用pd.concat((df_original, df_temp), axis=1) 结束。你会怎么做呢?
【问题讨论】:
-
在我看来你的双连接解决方案很好。