python - 如何将 pd.grouper 系列转换为 DataFrame

标签 python pandas datetime dataframe

我有这样的代码:

y1 = data.groupby(['name', pd.Grouper(key='datetime', freq='15d')])['ext price'].mean()
y=pd.DataFrame(y1)
y.head()

输出是:

                                    ext price
name        datetime    
Barton LLC  2014-01-01 07:21:51     3380.91
            2014-01-16 07:21:51     399.5228571
            2014-01-31 07:21:51     1666.523333
            2014-02-15 07:21:51     1804.615
            2014-03-02 07:21:51     1171.176667

我想将此输出作为 DataFrame 如下所示:

    name        datetime                ext price
0   Barton LLC  2014-01-01 07:21:51     3380.91
1   Barton LLC  2014-01-16 07:21:51     399.5228571
2   Barton LLC  2014-01-31 07:21:51     1666.523333
3   Barton LLC  2014-02-15 07:21:51     1804.615
4   Barton LLC  2014-03-02 07:21:51     1171.176667

最佳答案

使用reset_index:

print(y.reset_index())

reset_index 只是建立新的索引,将旧的级别作为列,并使数据帧正常。

输出:

    name        datetime                ext price
0   Barton LLC  2014-01-01 07:21:51     3380.91
1   Barton LLC  2014-01-16 07:21:51     399.5228571
2   Barton LLC  2014-01-31 07:21:51     1666.523333
3   Barton LLC  2014-02-15 07:21:51     1804.615
4   Barton LLC  2014-03-02 07:21:51     1171.176667

关于python - 如何将 pd.grouper 系列转换为 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53689721/

相关文章:

sql - 替换日期时间日期中的年份

python - 使用 1 个按钮 Django 提交 2 个自定义 Crispy 表单

python - 当 continue 命中时,是否有一种 Pythonic 方式在 'else' 循环中激活 'for'?

python - Librosa Keras 音乐分析神经网络 Python : Input Value Error

python - 如何从 pandas 的 groupby 函数中排除一个值

python - Pandas 数据框基于列值拆分列表

excel - 按日期和时间检索值的最新状态

Python 2.7 运行时代码更改

python - 如果任何列值不遵守 pandas 中的条件,则删除行

c# - 使用什么数据类型来存储 "MMYYYY"格式