首页 > 解决方案 > 从 pandas groupby 获取数据帧以写入镶木地板

问题描述

我有一些带有以下列的csv数据:

country, region, year, month, price, volume

我需要将其转换为以下内容:

country, region, datapoints

其中数据点由以下任一组成: (year, month, price, volume) 元组数组,或(更好)

{ (year, month) : {price, volume} }

实际上,我正在尝试将数据重塑为时间序列,然后可以将其存储为镶木地板。对于它的价值,我正在使用 fastparquet 将数据帧写入 parquet 文件。

这可能吗?

标签: pythonpandaspandas-groupbyparquetfastparquet

解决方案


您可以使用apply创建列“数据点”:

df['datapoint'] = df.apply(lambda row: (row['year'],row['month'],
                                         row['price'],row['volume']),1)

或者

df['datapoint_better'] = df.apply(lambda row: {(row['year'],row['month']):
                                                 {row['price'],row['volume']}},1)

正如我所说,你不能{row['year'],row['month']}作为字典中的键

然后,如果您想驾驭这些列:

df = df.drop(['year','month','price','volume'],1)

编辑:好的,我错过了 groupby,无论如何,您可以先使用键和项目创建两列:

df['key'] = df.apply(lambda row: ( row['year'], row['month']),1)
df['item'] = df.apply(lambda row: { row['price'], row['volume']},1)

然后你groupby用这两列apply来做和做,pd.Series.to_dict例如:

df_output = (df.groupby(['country','region'])
               .apply(lambda df_grouped: pd.Series(df_grouped.item.values,
                                                   index=df_grouped.key).to_dict())
               .reset_index().rename(columns={0:'datapoints'}))

reset_index并且rename是得到预期的输出

注意:我建议也使用tuple该项目,而不是set防止任何set未订购的订单问题。


推荐阅读