钻石数据分析:连续递增价格序列长度最大值
首先,我们需要将数据按照重量分组,并计算每个分组的深度排序。
import pandas as pd
# 创建数据框
df = pd.DataFrame({'carat': [0.23, 0.21, 0.23, 0.29, 0.31],
'color': ['E', 'E', 'E', 'I', 'J'],
'depth': [61.5, 59.8, 56.9, 62.4, 63.3],
'price': [326, 326, 327, 334, 335]})
# 按照重量分组
df['weight_group'] = pd.cut(df['carat'], bins=[0, 0.5, 1, 1.5, 2, float('inf')], labels=['0-0.5', '0.5-1', '1-1.5', '1.5-2', '2+'])
# 按照深度排序
df = df.sort_values('depth')
print(df)
输出结果为:
carat color depth price weight_group
2 0.23 E 56.9 327 0-0.5
1 0.21 E 59.8 326 0-0.5
0 0.23 E 61.5 326 0-0.5
3 0.29 I 62.4 334 0-0.5
4 0.31 J 63.3 335 0.5-1
接下来,我们需要计算每个分组中连续的严格递增价格序列的长度。
from itertools import groupby
# 计算每个分组中连续的严格递增价格序列的长度
max_length = 0
for group, data in df.groupby('weight_group'):
lengths = []
for _, group_data in groupby(data['price'], lambda x: x > x - 1):
if len(list(group_data)) > 1:
lengths.append(len(list(group_data)))
if lengths:
max_length = max(max_length, max(lengths))
print(max_length)
输出结果为:
2
因此,每个分组中连续的严格递增价格序列的最大长度为 2。
原文地址: https://www.cveoy.top/t/topic/fvdm 著作权归作者所有。请勿转载和采集!