- 验证
'all_maxs' 的值是list 类型。
- 从列表中提取值并将它们绘制为水平线。
-
df = df.dropna() 如果有的话NaN
导入和数据帧
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
情节
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')