我想根据剪切间隔自动设置合并直方图的标签。通过将pd.cut()应用于数据帧来创建数据仓。 pd.cut的列表是手动指定的(请参见切割列表),但我希望根据切割列表自动设置直方图标签。如何使用代码将切割清单转换为标签清单?
#cut list
cut = [0,20,40,60,80,100]
#desired label list
label = ['[0-20]', ']20-40]', ']60-80]', ']80-100]']
#to be used for:
pd_cut = pd.cut(df, cut, labels=label, include_lowest=True).astype(str)
您可以使用zip
进行配对,并不断更新列表label
:
cut = [0,20,40,60,80,100]
label = []
for i, p in enumerate(zip(cut, cut[1:])):
ob = '[' if i == 0 else ']'
label.append('{}{}-{}]'.format(ob, *p))
print(label)
输出:
['[0-20]', ']20-40]', ']40-60]', ']60-80]', ']80-100]']
除了zip
,enumerate
和切片之外,您还可以对range
和len
使用经典的for循环:
for i in range(len(cut) - 1):
ob = '[' if i == 0 else ']'
label.append('{}{}-{}]'.format(ob, cut[i], cut[i + 1]))