【问题标题】:ValueError: cannot reindex from a duplicate axisValueError:无法从重复的轴重新索引
【发布时间】:2016-05-17 09:54:57
【问题描述】:

假设我有两个数据框:

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,但这似乎非常低效。有没有更好的方法来做到这一点?

我知道有几个问题的标题相同,但没有一个对我的案例有任何帮助。

【问题讨论】:

  • 你期待什么结果?

标签: python pandas


【解决方案1】:

将索引设置为使用“i”中生成的值,然后根据该索引将 df2 连接到 df:

df = df.set_index(i)
df['new_col'] = df2['one']

【讨论】:

    【解决方案2】:

    您可以使用tolist 方法将您的df2.one 转换为列表,然后将其分配给df['new_col']:

    df['new_col'] = df2['one'][i].tolist()
    

    编辑

    或者您可以使用@ajcr 在评论中建议的.values 属性,这样更快:

    df['new_col'] = df2['one'][i].values
    

    时机

    In [100]: %timeit df2.one[i].tolist()
    1000 loops, best of 3: 275 µs per loop
    
    In [101]: %timeit df2.one[i].values
    1000 loops, best of 3: 252 µs per loop
    

    【讨论】:

    • 您可以改用.values,即df['new_col'] = df2.loc[i, 'one'].values。在这里创建列表比创建数组更昂贵。
    • @ajcr 谢谢,添加到答案中。时间表明它并没有那么快
    • @Anton 我敢打赌它会使用更大的数据框。
    猜你喜欢
    • 2015-02-26
    • 2020-05-23
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多