【问题标题】:Pandas: groupby first column and apply that to rest of df (store values in list)Pandas:groupby 第一列并将其应用于 df 的其余部分(将值存储在列表中)
【发布时间】:2021-11-28 00:49:14
【问题描述】:

我知道已经有很多类似的问题,但似乎没有一个适用于我的问题(或者我不知道如何应用它们)

所以我有一个 Pandas DataFrame,第一列中有重复的条目,但其余列中的值不同。

像这样:

     location      year     GDP     ...
0    AUT           1998     14...
1    AUT           2018     98...
2    AUS           1998     24...
3    AUS           2018     83...
...

我只想在“位置”中获取唯一条目,但将所有列及其值保留在一个列表中:

     location      year             GDP               ...
0    AUT           (1998, 2018)     (14..., 98...)
1    AUS           (1998, 2018)     (24..., 83...)
...

我试过了:

grouped = df_gdp_pop_years.groupby("Location")['Year'].apply(list).reset_index(name = "Year")

我尝试用 lambda 函数做同样的事情,但我总是遇到同样的问题:我只保留年份。

我怎样才能得到我想要的结果?

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    你可以试试

    df_gdp_pop_years.groupby("Location").agg({"Year": list, "GDP": list})
    

    【讨论】:

      【解决方案2】:

      如果您的其他列可能正在更改或可能添加更多列,您可以在这些列上使用通用 .agg() 来完成此操作:

      df_gdp_pop_years.groupby('location').agg(lambda x: x.tolist())
      

      我通过搜索“pposite of pandas explode”发现了这一点,这导致我提出了一个不同的 SO 问题:How to implode(reverse of pandas explode) based on a column

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 2019-12-14
        相关资源
        最近更新 更多