【问题标题】:Pandas: InvalidIndexError: Reindexing only valid with uniquely valued Index objectsPandas:InvalidIndexError:重新索引仅对具有唯一值的索引对象有效
【发布时间】:2018-10-27 13:59:57
【问题描述】:

我有两个数据框,用于存储有关在商店中采购的产品的数据。 df1 存储有关商店名称、产品 ID、产品名称和购买日期的数据。 df2 存储有关产品 ID、产品名称和类型的数据。我正在尝试使用df1 中的接收日期值更新df2,但仅适用于P 类型的产品。

下面是数据框的视图以及我尝试做的事情。

df1:

StoreName,ProdId,ProdName,DateReceived
Store A,P1,Prod1,2018-05-01
Store A,P2,Prod2,2018-05-02
Store B,P1,Prod1,2018-05-04

df2:

DateRecived,ProdId,ProdName,Type

,P1,Prod1,P
,P2,Prod2,P
,P3,Prod3,S

脚本:

df2['DateRecived'] = df2['ProdId'].map(df1.set_index('ProdId')['StoreName']).df2['Type'] == 'P'

运行此程序会引发以下错误:

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

谁能帮我修改脚本,以便我能够过滤出 Store NameProd Name 的值,并让 df2 填充 DateReceived 值。谢谢。

【问题讨论】:

  • @jezrael,我试图通过 Type = P 过滤掉 Dataframe,因此试图将其附加到条件的末尾。基本上,我正在寻找的输出是按商店名称、产品名称和类型 = P 作为输出的一部分进行过滤..
  • 是的,刚刚意识到:)

标签: python pandas dataframe


【解决方案1】:

问题是重复的 - P1 产品是两次:

s = df1.set_index('ProdId')['StoreName']
print (s)

ProdId
P1    Store A
P2    Store A
P1    Store B
Name: StoreName, dtype: object

所以需要唯一值,drop_duplicates 只保留第一个值:

s = df1.drop_duplicates('ProdId').set_index('ProdId')['StoreName']
print (s)
ProdId
P1    Store A
P2    Store A
Name: StoreName, dtype: object

然后可以通过布尔掩码替换:

mask = df2['Type'] == 'P'
df2['DateRecived'] = df2['DateRecived'].mask(mask, df2['ProdId'].map(s))
print (df2)
  DateRecived ProdId ProdName Type
0     Store A     P1    Prod1    P
1     Store A     P2    Prod2    P
2         NaN     P3    Prod3    S

df2.loc[mask, 'DateRecived'] = df2.loc[mask, 'ProdId'].map(s)
print (df2)
  DateRecived ProdId ProdName Type
0     Store A     P1    Prod1    P
1     Store A     P2    Prod2    P
2         NaN     P3    Prod3    S

【讨论】:

  • 能否请我再寻求帮助。如果我说我们在 df1 中还有一个名为 Sub-Category 的列,并且希望将其包含在最终的 Dataframe 中,我们该如何修改它。谢谢..
  • @darkhorse - 我认为最简单的是s1 = df1.drop_duplicates('ProdId').set_index('ProdId')['Sub-Category'] df2.loc[mask, 'Sub-Category'] = df2.loc[mask, 'ProdId'].map(s1)
猜你喜欢
  • 2023-04-02
  • 2022-07-15
  • 2021-07-22
  • 2021-05-22
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多