【问题标题】:How to plot a dataframe column of lists as horizontal lines如何将列表的数据框列绘制为水平线
【发布时间】:2021-12-20 22:24:16
【问题描述】:

我有一个带有 'all_maxs' 列的 Dataframe,它可能有一个不同值的列表。

          c            all_maxs
38  50804.6           [50883.3]
39  50743.9           [50883.3]
40  50649.9           [50883.3]
41  50508.3           [50883.3]
42  50577.6           [50883.3]
43  50703.0           [50883.3]
44  50793.7           [50883.3]
45  50647.8  [50883.3, 50813.1]
46  50732.8  [50883.3, 50813.1]
47  50673.2  [50883.3, 50813.1]

df.plot(y='c')

当前结果

我需要绘制列'c',以及列'all_maxs' 的值应该是水平线。

预期结果

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:
    1. 验证'all_maxs' 的值是list 类型。
    2. 从列表中提取值并将它们绘制为水平线。
      • df = df.dropna() 如果有的话NaN

    导入和数据帧

    • 如果需要,使用ast.liter_eval'all_maxs' 列类型从str 转换为list
    import pandas as pd
    from ast import literal_eval
    
    data =\
    {38: {'all_maxs': '[50883.3]', 'c': 50804.6},
     39: {'all_maxs': '[50883.3]', 'c': 50743.9},
     40: {'all_maxs': '[50883.3]', 'c': 50649.9},
     41: {'all_maxs': '[50883.3]', 'c': 50508.3},
     42: {'all_maxs': '[50883.3]', 'c': 50577.6},
     43: {'all_maxs': '[50883.3]', 'c': 50703.0},
     44: {'all_maxs': '[50883.3]', 'c': 50793.7},
     45: {'all_maxs': '[50883.3, 50813.1]', 'c': 50647.8},
     46: {'all_maxs': '[50883.3, 50813.1]', 'c': 50732.8},
     47: {'all_maxs': '[50883.3, 50813.1]', 'c': 50673.2}}
    
    df = pd.DataFrame.from_dict(data, orient='index')
    
    # reorder the columns to match the OP
    df = df[['c', 'all_maxs']]
    
    # print a value from all_maxs to see the type
    >>> print(type(df.loc[38, 'all_maxs']))
    str
    
    # currently the all_max values are strings, which must be converted to list type
    df.all_maxs = df.all_maxs.apply(literal_eval)
    
    # print a value from all_maxs to see the type
    >>> print(type(df.loc[38, 'all_maxs']))
    list
    

    情节

    • 直接用pandas.DataFrame.plot绘制数据框
      • xticks=df.index 将为索引中的每个值创建一个 xtick,但如果有很多值拥挤在 x 轴上,请删除此参数。
    • 使用将接受值列表的matplotlib.pyplot.hlines'all_max' 中的唯一值绘制为水平线。
      • 使用pandas.DataFrame.explode 删除列表中的所有值,然后使用.drop_duplicates 删除重复项
      • y= 将是 'all_maxs' 列中的剩余值
      • xmin= 将是剩余的索引值
      • xmax= 将是从df 绘制的索引中的最大值
    ax = df.plot(y='c', legend=False, figsize=(8, 5), xticks=df.index)
    
    # extract all the values from all_maxs, drop the duplicates
    all_maxs = df.all_maxs.explode().drop_duplicates().to_frame()
    
    # add the horizontal lines
    ax.hlines(y=all_maxs.all_maxs, xmin=all_maxs.index, xmax=df.index.max(), color='k')
    

    【讨论】:

    • 代码完美。我试图达到相同结果的方法要慢得多。我很抱歉我的坏问题。下次我会按照你的更正。谢谢
    • @Gabriele 这不是一个坏问题,它只是没有 SO 问题所期望的所有必要信息或代码。处理数据框中的列表并绘制它们实际上是一个有趣的问题。我很高兴这对你有用。
    猜你喜欢
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多