【问题标题】:Trouble specifying column names when making dataframe from aggregate function从聚合函数制作数据框时无法指定列名
【发布时间】:2019-06-24 07:09:12
【问题描述】:

当我创建一个数据框时:

freq = pd.DataFrame(combined.groupby(['Latitude', 'Longitude','from_station_name']).agg('count')['trip_id'])

它工作得很好,但是当我尝试时:

freq = pd.DataFrame(combined.groupby(['Latitude', 'Longitude','from_station_name']).agg('count')['trip_id'], columns = ['lat','long','station','trips'])

当我查看数据框时,我只看到标题。我可以制作数据框,然后使用:

freq.columns = ['lat','long','station','trips']

但想知道如何一步完成。我尝试为聚合函数指定“data =”。尝试将列名的括号括起来,删除列名的括号。任何建议表示赞赏。

【问题讨论】:

  • combined.groupby(['Latitude', 'Longitude','from_station_name']).agg('count') 返回一个DataFrame,传递给DataFrame构造函数的目的是什么?您可以简单地重置索引并重命名列:combined.groupby(['Latitude', 'Longitude','from_station_name']).agg('count').reset_index().rename({'attitude':'lat'.. ....
  • @Vaishali 我只是想把它归结为一个步骤。当我做一个导致一系列的聚合时,我看到了同样的行为。例如:latcounts = pd.DataFrame(combined.groupby('Latitude').agg('count'),columns = ['lat','count'])

标签: pandas dataframe pandas-groupby kaggle


【解决方案1】:

您不需要将 groupby 对象传递给新的数据框构造函数(就像已经提到的 @Vaishali)

如果您想在 groupby 之后重命名列,您可以简单地执行以下操作:

combined.groupby(['Latitude', 'Longitude','from_station_name']).trip_id.agg('count').rename(columns={'Latitude': 'lat', 'Longitude': 'long', 'from_station_name':'station', 'count': 'trips})

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 2018-10-27
    • 2021-11-14
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多