【问题标题】:How to method chain .agg() and .assign() functions in Pandas如何在 Pandas 中链接 .agg() 和 .assign() 函数
【发布时间】:2020-03-18 12:58:43
【问题描述】:

我希望在 Pandas 中复制这个 Dplyr 查询,但是在将 .agg().assign() 函数链接在一起时遇到了麻烦,而且会这样感谢您的任何建议

Dplyr代码:

counties_selected %>%
  group_by(state) %>%
  summarize(total_area = sum(land_area),
            total_population = sum(population)) %>%
  mutate(density = total_population / total_area) %>%
  arrange(desc(density))

Pandas 中进行同样的尝试:
在 .assign() 部分中,我将变量重定向回原始数据帧,但没有其他工作

counties.\
   groupby('state').\
   agg(total_area = ('land_area', 'sum'),
       total_population = ('population', 'sum')).\
   reset_index().\
   assign(density = counties['total_population'] / counties['total_area']).\
   arrange('density', ascending = False).\
   head()

【问题讨论】:

    标签: pandas data-manipulation method-chaining


    【解决方案1】:

    问题是您需要lambda 来处理链式数据,并且已经在以前的链式方法中处理:

    assign(density = counties['total_population'] / counties['total_area'])
    

    到:

    assign(density = lambda x: x['total_population'] / x['total_area'])
    

    另一个问题是使用排序来代替:

    arrange('density', ascending = False)
    

    方法DataFrame.sort_values:

    sort_values('density', ascending = False):
    

    总的来说,. 用于启动方法,例如:

    df = (counties.groupby('state')
                  .agg(total_area = ('land_area', 'sum'),
                       total_population = ('population', 'sum'))
                  .reset_index()
                  .assign(density = lambda x: x['total_population'] / x['total_area'])
                  .sort_values('density', ascending = False)
                  .head())
    

    【讨论】:

    • 非常感谢您的回复和分享您的知识,它工作得很好,但是有没有办法也链接 .arrange() 部分?它似乎没有选择新的变量“密度”。
    • @RobertChestnutt - 抱歉,我想念它,答案已编辑。
    【解决方案2】:

    使用datar,可以轻松地将您的 dplyr 代码移植到 python 代码,而无需学习 pandas API:

    from datar.all import f, group_by, summarize, sum, mutate, arrange, desc
    
    counties_selected >> \
      group_by(f.state) >> \
      summarize(total_area = sum(f.land_area),
                total_population = sum(f.population)) >> \
      mutate(density = f.total_population / f.total_area) >> \
      arrange(desc(f.density))
    

    我是包的作者。如果您有任何问题,请随时提交问题。

    【讨论】:

      猜你喜欢
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2014-03-16
      • 2015-02-10
      • 1970-01-01
      相关资源
      最近更新 更多