【问题标题】:Pandas - Reindexing only valid with uniquely valued Index objectsPandas - 重新索引仅对具有唯一值的索引对象有效
【发布时间】:2021-05-22 01:42:32
【问题描述】:

我有两个数据框:

df1 = pd.DataFrame({'player_id':[86508, 86509, 86508,86509 ], 
                    'match_id': [243061,243061, 243062, 243062], 
                    'line_up':[1,1,1,1]})

和:

df2 = pd.DataFrame({'player_id':[86508, 86509, 86508, 86509 ], 
                    'match_id': [243061,243061, 243062, 243062]})

我需要将“line_up”值从df1 带到df2,基于“player_id”。我试过用map():

df2['line_up'] = df2['player_id'].map(df1.set_index('player_id')['line_up'])

但这会给我带来错误:

pandas.core.indexes.base.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

还有其他简单的解决方法吗?

玩家 ID 会重复很多次,并且不能删除重复的 ID,因为每一轮 (match_id) 都很重要。

【问题讨论】:

  • 可能删除重复项:df2.player_id.map(df1.set_index("player_id").line_up.drop_duplicates())?
  • 很遗憾,无法完成。
  • 您不能删除重复项?做不到是什么意思?
  • 我没有明白你删除重复项的意思。我以为你的意思是删除有 player_id dup 的行

标签: python pandas


【解决方案1】:

这对我有用;

df2['line_up'] = df2['player_id'].map(dict(zip(df1['player_id'],df1['line_up'])))

不过,我认为使用您的方法如下。

df2['line_up'] = df2['player_id'].map(df1.set_index('player_id')['line_up'].to_dict())

【讨论】:

  • dict 部分将删除重复项,因为在字典中,您只能拥有唯一键
【解决方案2】:

dfs 将通过赋值加入索引(而不是行)。你可以这样做:

df2 = df2.set_index("player_id")
df2["line_id"] = df1.set_index("player_id")["line_up"]
df2 = df2.reset_index()

输出:

   player_id  match_id  line_vals
0      86508    243061          1
1      86509    243061          1
2      86508    243062          1
3      86509    243062          1

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2023-04-02
    • 2022-07-15
    • 2021-07-22
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多