【问题标题】:pandas -- multiple rows per observation with repeated and non-repeated valuespandas - 每个观察多行,具有重复和非重复值
【发布时间】:2022-01-23 01:17:33
【问题描述】:

我有数据,其中每个观测值都有唯一的 id 和月份,但多个观测值具有相同的 id 或月份。

目前,数据每行有不止一个观测值,因为每个观测值都会为观测值拥有的每个大陆增加一行。不是将大洲组合在一个列表中或分解为多列,而是在多行中重复观察的所有值,但大洲列除外,该列对于观察中的每一行都有唯一的值。

    id  month   continent   species color
0   51451   jan africa  penguin red
1   51451   jan s america   penguin red
2   51451   feb n america   penguin red
3   51451   feb asia    penguin red
4   68321   jul asia    lion    blue
5   464316  jul africa  monkey  blue
6   51451   oct africa  dog grey
7   51451   oct s america   dog grey
8   51451   oct europe  dog grey

数据只需要整洁。将每个观测值的多个唯一大陆值合并到一个列表中可能效果最好:

    id  month   continent   species color
0   51451   jan "[""africa"", ""s america""]"   penguin red
1   51451   feb "[""n america"", ""asia""]" penguin red
2   68321   jul "[""asia""]"    lion    blue
3   464316  jul "[""africa""]"  monkey  blue
4   51451   oct ['africa', 's america', 'europe']   dog grey

我觉得 GroupBy 是这里的答案,

df.groupby(['id', 'month']). ...

但找不到适用于此处的属性。 .unique() 显然只适用于 SeriesGroupBy。 (对吗?)有没有可以在这里工作的属性?还是有与 GroupBy 不同的方向来尝试? .agg(list) 接近了,只需要清理一下:

df = df.groupby(['id','month']).agg(list)

df[['species', 'color']] = df[['species', 'color']].applymap(
    lambda x: x[0] if (len(np.unique(x))==1) else x
)

不过,这似乎有点笨拙。 .agg(lambda x: list(set(x))) 摆脱了一些工作,但仍然需要返回并弹出最后两列以获得所需的输出:

df[['species', 'color']] = df[['species', 'color']].applymap(
    lambda x: x.pop()
)

【问题讨论】:

  • df.groupby(['id','month']).agg(list) 怎么样,可以吗?或者对于每个列表中的唯一值df.groupby(['id','month']).agg(lambda x: list(set(x)))
  • 抱歉,您的意思是什么需要清理一下?你想达到什么目标?

标签: python pandas dataframe group-by


【解决方案1】:

如果我理解正确,您希望大陆下的结果是一个列表,物种和颜色下的结果是字符串:

f = lambda l: ','.join(np.unique(l))
df.groupby(['id','month']).agg({'continent':'unique','species':f,'color':f})

id     month                                            
51451  feb              [n america, asia]  penguin   red
       jan            [africa, s america]  penguin   red
       oct    [africa, s america, europe]      dog  grey
68321  jul                         [asia]     lion  blue
464316 jul                       [africa]   monkey  blue

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2020-09-05
    • 2020-09-04
    • 1970-01-01
    • 2017-05-18
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多