python Pandas : pivot only certain columns in the DataFrame while keeping others

标签 python pandas pivot-table

我正在尝试重新安排我使用 Pandas 从 json 中自动读取的 DataFrame。我搜索过但没有成功。

我有以下 json(为方便复制/粘贴而保存为字符串),在“值”标签下有一堆 json 对象/字典

json_str = '''{"preferred_timestamp": "internal_timestamp",
    "internal_timestamp": 3606765503.684,
    "stream_name": "ctdpf_j_cspp_instrument",
    "values": [{
        "value_id": "temperature",
        "value": 9.8319
    }, {
        "value_id": "conductivity",
        "value": 3.58847
    }, {
        "value_id": "pressure",
        "value": 22.963
    }]
}'''

我使用“json_normalize”函数将 json 加载到扁平化的 Pandas 数据框中。

>>> from pandas.io.json import json_normalize
>>> import simplejson as json
>>> df = json_normalize(json.loads(json_str), 'values', ['preferred_timestamp', 'stream_name', 'internal_timestamp'])
>>> df
      value      value_id preferred_timestamp  internal_timestamp  \
0   9.83190   temperature  internal_timestamp        3.606766e+09   
1   3.58847  conductivity  internal_timestamp        3.606766e+09   
2  22.96300      pressure  internal_timestamp        3.606766e+09   
3  32.89470      salinity  internal_timestamp        3.606766e+09   

               stream_name  
0  ctdpf_j_cspp_instrument  
1  ctdpf_j_cspp_instrument  
2  ctdpf_j_cspp_instrument  
3  ctdpf_j_cspp_instrument  

这就是我被困的地方。我想获取 value 和 value_id 列并将它们转换为基于 value_id 的新列。

我希望数据框如下所示:

stream_name              preferred_timestamp  internal_timestamp  conductivity  pressure  salinity  temperature    
ctdpf_j_cspp_instrument  internal_timestamp   3.606766e+09        3.58847       22.96300  32.89470  9.83190

我已经尝试过 pivot 和 pivot_table Pandas 函数,甚至尝试使用“set_index”和“stack”手动旋转表格,但这并不是我想要的。

>>> df.pivot_table(values='value', index=['stream_name', 'preferred_timestamp', 'internal_timestamp', 'value_id'])
stream_name              preferred_timestamp  internal_timestamp  value_id    
ctdpf_j_cspp_instrument  internal_timestamp   3.606766e+09        conductivity     3.58847
                                                                  pressure        22.96300
                                                                  salinity        32.89470
                                                                  temperature      9.83190
Name: value, dtype: float64

这很接近,但它似乎没有将“value_id”中的值旋转到单独的列中。

>>> df.pivot('stream_name', 'value_id', 'value')
value_id                 conductivity  pressure  salinity  temperature
stream_name                                                           
ctdpf_j_cspp_instrument       3.58847    22.963   32.8947       9.8319

再次关闭,但它缺少我想要与此行相关联的其他列。

我被困在这里了。有没有一种优雅的方法可以做到这一点,或者我应该拆分 DataFrame 并将它们重新合并到我想要的方式?

最佳答案

您的第一次尝试几乎是正确的,只需使用 columns='value_id' 而不是将其包含在索引中。

# Perform the pivot.
df = df.pivot_table(
    values='value',
    index=['stream_name', 'preferred_timestamp', 'internal_timestamp'],
    columns='value_id'
    )

# Formatting.
df.reset_index(inplace=True)
df.columns.name = None

这在您的示例数据中不是问题,但请记住,如果多个值被旋转到同一位置(默认取平均值),pivot_table 将聚合值。

关于 python Pandas : pivot only certain columns in the DataFrame while keeping others,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36019788/

相关文章:

python - 如何将参数从全局模型复制到线程特定模型

尝试在 lldb 中继续处理时 Python 脚本卡住

python - 在 Pandas 中为层次索引的内部维度选择不同的值

vba - Excel VBA - 数据透视表筛选器运行时错误 '1004' 数据透视项

excel - 将矩阵转换为 3 列表 ('reverse pivot' 、 'unpivot' 、 'flatten' 、 'normalize' )

pivot-table - Pivot 或 clickhouse 中的同等功能

python - Python 中的继承

python - 将两个数据框合并到一个公共(public)索引上(无需创建单独的行)

python - Pandas 数学运算,以列值为条件

python - 在 Pandas 中使用衰减公式进行插值/填充