假设我有两个数据帧:
import string
import pandas as pd
d = {'one': pd.Series(range(26), index = list(string.ascii_lowercase)),
'two': pd.Series([1., 2., 3., 4.], index = ['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
d2 = {'one': pd.Series(range(10), index = range(11, 21))}
df2 = pd.DataFrame(d2)
现在,我有一个索引列表:
np.random.seed(12)
i = np.random.choice(np.arange(11, 21), size = 26)
现在我想基于 i
加入 df2
与 df1
.
df['new_col'] = df2['one'][i]
但是我得到了上面提到的错误 . 解决此问题的一种方法是直接将 i
添加到 df1
,并在 df2
中创建一个名为 i
的列来表示 index
,然后执行 merge
但看起来非常低效 . 有一个更好的方法吗?
我知道有几个问题有相同的 Headers ,但没有一个对我的案例有任何帮助 .
2 回答
您可以使用
tolist
方法将df2.one
转换为列表,然后将其分配给df['new_col']
:EDIT
或者您可以使用
.values
属性作为评论中建议的@ajcr更快:Timing
设置索引以使用'i'中生成的值,然后根据该索引将df2连接到df: