【问题标题】:Extracting and Grouping Sets of Columns in a Pandas DataFrame在 Pandas DataFrame 中提取和分组列集
【发布时间】:2017-09-09 04:31:22
【问题描述】:

我有一个从 CSV 文件中派生的 DataFrame 结构,该文件涉及多年的人口统计数据。即,文件中的列是每月的时间间隔(1999-01、1999-02 ... 2016-12),行是世界上不同的人口中心(例如伦敦、多伦多、波士顿等):

df = pd.DataFrame({'1999-01' : [100, 5000, 8000], '1999-02' : [200, 6000, 9000], '1999-03' : [300, 7000, 10000], ..., cities : ['CityA', 'CityB', 'CityC' ...]})

我想按季度分隔这些列。因此,我将为每一行取 1999-01、1999-02、1999-9 的平均人口,并为此条目创建一个新列“1999Q1”,每 3 个月执行一次:

df_quarter = pd.DataFrame({'1999Q1' : [200, 6000, 9000], '1999Q2' : ..., cities = ['CityA', 'CityB', 'CityC' ...]})

#Q1 corresponds to months 01-03, Q2 to months 04-06, Q3 to months 07-09, Q4 months 10-12, all inclusive

但是,我很难将查询概念化以完成此操作。我有一半的想法先使用 .groupby(),然后使用 .agg(),但我不确定如何有效地指定 3 列分组并遍历列。有人可以指出我正确的方向吗?

编辑:假设列不是日期,而是更抽象的东西,并且不能使用简单的时间段重采样。例如:

#Prices of different foods from different vendors
df = pd.DataFrame({'oranges' : [2, 3, 7], 'apples' : [6, 3, 9], 'cheese' : [13, 9, 11], 'milk' : [6, 5, 12], 'vendors' : ['VendorA', 'VendorB', 'VendorC']})

现在,如果我想创建两列,结合水果和奶制品,有什么方法可以指定要聚合的索引吗?

【问题讨论】:

  • 请阅读this 并学习如何提出一个好的熊猫问题。没有人会凭空为您提供示例和解决方案。
  • 将进行适当的编辑。

标签: python pandas dataframe pandas-groupby


【解决方案1】:

您可以先将to_datetime 列转换为month period,然后将to_period 转换为resample,然后按列(axis=1) 和quarter (q) 与聚合mean

df = pd.DataFrame({'1999-01':[4,5,4,5,5,4],
                   '1999-02':[7,8,9,4,2,3],
                   '1999-03':[1,3,5,7,1,0],
                   '1999-04':[1,3,5,7,1,0],
                   '1999-05':[5,3,6,9,2,4]}, index=list('abcdef'))

print (df)
   1999-01  1999-02  1999-03  1999-04  1999-05
a        4        7        1        1        5
b        5        8        3        3        3
c        4        9        5        5        6
d        5        4        7        7        9
e        5        2        1        1        2
f        4        3        0        0        4

df.columns = pd.to_datetime(df.columns).to_period('m')
df = df.resample('q', axis=1).mean()

print (df)
     1999Q1  1999Q2
a  4.000000     3.0
b  5.333333     3.0
c  6.000000     5.5
d  5.333333     8.0
e  2.666667     1.5
f  2.333333     2.0

【讨论】:

  • 请停止鼓励低质量的问题。如果是其他人回答,我会立即投反对票。通过回答此类问题,您鼓励了更多此类问题,您知道这些问题对未来除了 OP 之外的任何人都没有帮助。
  • @cᴏʟᴅsᴘᴇᴇᴅ - 谢谢。嗯,我同意如果输入数据、所需的输出、代码很好,最好回答。这是理想的。但有时可以从文本中理解 OP 需要什么。所以看来我明白了,所以我创建了答案。
  • 我在这里同意@cᴏʟᴅsᴘᴇᴇᴅ。如果我们仍然想继续回答,我认为,OP 或回答者应该重新格式化问题/添加详细信息以便更好地使用。
  • 啊,我应该更好地利用 pandas 中的 datetime 函数。谢谢。
猜你喜欢
  • 2020-01-28
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2018-06-20
  • 2018-04-07
  • 2018-09-04
相关资源
最近更新 更多