python - 在 DataFrame 的列中而不是行中表达时间序列数据

标签 python pandas time-series

我正在努力阐明我的问题,因此我将通过示例进行演示。

假设我有一个如下所示的 DataFrame:

>>> df = pd.DataFrame([{'person': 'bob', 'year': 2016, 'production': 30, 'efficiency': .10}, {'person': 'bob', 'year': 2017, 'production': 35, 'efficiency': .11}, {'person': 'bob', 'year': 2018, 'production': 15, 'efficiency': .05}])
>>> df
   efficiency person  production  year
0        0.10    bob          30  2016
1        0.11    bob          35  2017
2        0.05    bob          15  2018

我需要生成一份报告,其中一行包含每个人的所有信息。因此,我想将上面的内容转换为:

   efficiency 2016 person  production 2016  efficiency 2017  production 2017  \
0              0.1    bob               30             0.11               35

   efficiency 2018  production 2018
0             0.05               15

这段代码能够进行这种转换,但效率非常低:

def combine_years(df):
    final_df = None
    for name, stats in df.groupby('person'):
        agg_df = None
        for year in stats['year']:
            new_df = stats[stats.year == year].rename(columns=lambda colname: column_renamer(colname, year))
            new_df = new_df.drop('year', axis=1)
            if agg_df is None:
                agg_df = new_df
            else:
                agg_df = agg_df.merge(new_df, how='outer', on=['person'])
        if final_df is None:
            final_df = agg_df
        else:
            final_df = pd.concat([final_df, agg_df], axis=1)
    return final_df

几个问题:

  1. 这种类型的转换有更通用的名称吗?
  2. 有没有办法使用 pandas 提供的函数更有效地完成此操作?

最佳答案

set_index

我希望'person'最终出现在index中,并将columns保留为pandas.MultiIndex

df.set_index(['person', 'year']).unstack().swaplevel(0, 1, 1).sort_index(1)

year         2016                  2017                  2018           
       efficiency production efficiency production efficiency production
person                                                                  
bob           0.1         30       0.11         35       0.05         15
<小时/>

数据透视表

df.pivot_table(index='person', columns='year').swaplevel(0, 1, 1).sort_index(1)

year         2016                  2017                  2018           
       efficiency production efficiency production efficiency production
person                                                                  
bob           0.1         30       0.11         35       0.05         15

关于python - 在 DataFrame 的列中而不是行中表达时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54915215/

相关文章:

python - Pandas:删除重复的日期但保留最后一个

python-3.x - Pandas - KeyError : 'cannot use a single bool to index into setitem'

python - 如何将分层命名的列添加到 Pandas DataFrame

R 在 R 中使用引用时间表过滤数据

python - Pandas 时间序列增量的回归

python - SimpleXMLRPCServer 可以监听多个地址吗?

Python:两个列表之间的成对比较:list a >= list b?

python - 安装 ROS Kinetic 后无法导入 OpenCV

python - Python 中的时间序列可达微秒

r - 根据 R 中缺失数据的时间序列计算周平均值