python - 从 pandas groupby 获取数据帧以写入镶木地板
问题描述
我有一些带有以下列的csv数据:
country, region, year, month, price, volume
我需要将其转换为以下内容:
country, region, datapoints
其中数据点由以下任一组成:
(year, month, price, volume)
元组数组,或(更好)
{
(year, month) : {price, volume}
}
实际上,我正在尝试将数据重塑为时间序列,然后可以将其存储为镶木地板。对于它的价值,我正在使用 fastparquet 将数据帧写入 parquet 文件。
这可能吗?
解决方案
您可以使用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
未订购的订单问题。
推荐阅读
- c++ - 交换链表的最后一个节点将进入无穷大——C++
- javascript - 在构造函数中同步加载图像
- r - 将空格分隔的文本文件转换为命名向量以计算 HWE
- javascript - Nuxt.JS “预期参数 accessToken” 内容丰富
- css - 如何在 MDN 上阅读 CSS 语法
- java - 我在递归实现字符串的子字符串方法时遇到了麻烦
- docker - 尝试将数据处理分布在集群中,然后将其聚合到主服务器中
- c# - Xamarin Checkbox 未正确“链接”到 App.xaml.cs 中的 ObservableCollection
- java - 有人可以教我如何解释 javax.net.debug 结果吗?
- javascript - 将逗号分隔的数据类型转换为json有效源