如何用Pandas合并多组读数列表并提取指定特征的最大值?
使用Pandas合并多组读数并提取指定元素的最大读数
当然可以用Pandas轻松实现这个需求!针对你提供的数据集,我们可以快速合并所有读数列表,然后精准提取aoiFeatures中每个元素对应的最大读数。
给定数据
# FYI: 2.4 million elements in each of these lists in reality allFeatures = [101, 179, 181, 183, 185, 843, 845, 847, 849, 851] allReadings1 = [0.27, 0.25, 0.13, 0.04, 0.05, 0.09, 0.15, 0.13, 0.12, 0.20] allReadings2 = [0.25, 0.06, 0.29, 0.29, 0.04, 0.21, 0.07, 0.06, 0.07, 0.06] allReadings3 = [0.12, 0.02, 0.20, 0.27, 0.04, 0.08, 0.11, 0.24, 0.00, 0.13] allReadings4 = [0.21, 0.00, 0.22, 0.11, 0.24, 0.16, 0.11, 0.18, 0.27, 0.14] allReadings5 = [0.02, 0.18, 0.26, 0.22, 0.23, 0.15, 0.24, 0.28, 0.00, 0.07] allReadings6 = [0.08, 0.25, 0.21, 0.23, 0.14, 0.21, 0.18, 0.09, 0.17, 0.27] allReadings7 = [0.20, 0.02, 0.28, 0.16, 0.18, 0.27, 0.29, 0.19, 0.29, 0.13] allReadings8 = [0.17, 0.01, 0.07, 0.23, 0.14, 0.20, 0.19, 0.01, 0.15, 0.17] allReadings9 = [0.12, 0.18, 0.09, 0.10, 0.00, 0.03, 0.11, 0.03, 0.14, 0.14] allReadings10 =[0.13, 0.03, 0.20, 0.13, 0.30, 0.30, 0.28, 0.12, 0.19, 0.22] # FYI: 67,000 elements in this list in reality aoiFeatures = [181, 843, 849]
解决方案代码
import pandas as pd # 创建DataFrame,用allFeatures作为行索引,每个读数列表作为一列 df = pd.DataFrame({ 'reading1': allReadings1, 'reading2': allReadings2, 'reading3': allReadings3, 'reading4': allReadings4, 'reading5': allReadings5, 'reading6': allReadings6, 'reading7': allReadings7, 'reading8': allReadings8, 'reading9': allReadings9, 'reading10': allReadings10 }, index=allFeatures) # 计算每个feature对应的所有读数的最大值,新增一列存储 df['max_reading'] = df.max(axis=1) # 筛选出aoiFeatures对应的行,提取结果 target_results = df.loc[aoiFeatures, 'max_reading'] # 按照预期格式输出 for feature, max_val in target_results.items(): print(f"{feature} {max_val}")
代码说明
- 首先我们用
pd.DataFrame把所有读数数据整合到一个表格中,用allFeatures的值作为行索引,这样每个feature和它的所有读数就一一对应了。 df.max(axis=1)会计算每行(也就是每个feature)的所有读数中的最大值,把结果存入新列max_reading。- 最后用
loc方法精准筛选出aoiFeatures中的元素对应的行,就能得到我们需要的最大读数了。
运行结果
181 0.29 843 0.27 849 0.29
注意: 针对你提到的百万级别的数据量,Pandas的性能完全可以胜任,这种处理方式在大数据量下依然高效。
内容的提问来源于stack exchange,提问作者JackedUpDBA
相关产品推荐
相关产品推荐

