【问题标题】:pandas change attribute values to row values of object熊猫将属性值更改为对象的行值
【发布时间】:2019-08-28 15:40:03
【问题描述】:

此时从文件中解析的数据聚合:

obj    price1*red    price1*blue    price2*red    price2*blue
a      5             7              10            12
b      15            17             20            22

期望的结果:

obj    color    price1    price2
a      red      5         7
a      blue     10        12
b      red      15        17
b      blue     20        22

这个例子被简化了。实际用例的数据保留在 404 列和 10'000 行中。数据大多有大约99个位置的颜色和4种不同的价格表(价格表总是4种)。

我已经尝试了与之前在 python 中编写的另一部分不同的方法

df_pricelist = pd.melt(df_pricelist, id_vars=["object_nr"], var_name='color', value_name='prices')

但这种方法最初用于将数据从单个属性转换为多行。或者换句话说,不同的价目表只有 1 个单元格,而不是多个单元格。

我还使用 assign 将字符串的不同块添加到不同的列单元格。

要将所有不同的列放入数据框中,我使用 str.startswith。这样我就不必知道可能存在的所有不同颜色。

【问题讨论】:

    标签: python pandas pivot multiple-columns rows


    【解决方案1】:

    使用MultiIndex 作为中间步骤的解决方案:

    import pandas as pd
    
    # Construct example dataframe
    col_names = ["obj", "price1*red", "price1*blue", "price2*red", "price2*blue"]
    data = [
        ["a", 5, 7, 10, 12],
        ["b", 15, 17, 20, 22],
    ]
    df = pd.DataFrame(data, columns=col_names)
    
    # Convert objects column into rows index
    df2 = df.set_index("obj")
    
    # Convert columns index into two-level multi-index by splitting name strings
    color_price_pairs = [tuple(col_name.split("*")) for col_name in df2.columns]
    df2.columns = pd.MultiIndex.from_tuples(color_price_pairs, names=("price", "color"))
    
    # Stack colors-level of the columns index into a rows index level
    df2 = df2.stack()
    df2.columns.name = ""
    
    # Optional: convert rows index (containing objects and colors) into columns
    df2 = df2.reset_index()
    

    这是显示原始数据帧df 和结果数据帧df2 的打印输出:

    In [1] df
    Out[1]: 
      obj  price1*red  price1*blue  price2*red  price2*blue
    0   a           5            7          10           12
    1   b          15           17          20           22
    
    In [2]: df2
    Out[2]: 
      obj color  price1  price2
    0   a  blue       7      12
    1   a   red       5      10
    2   b  blue      17      22
    3   b   red      15      20
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 2020-07-11
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2019-03-09
      • 2023-03-08
      • 2016-07-09
      相关资源
      最近更新 更多