Python Dataframe列表列处理:提取x列公共值及对应y列数值
完整实现代码
首先导入依赖库:
import pandas as pd from functools import reduce
构造测试数据(实际使用时替换为你自己的DataFrame即可):
df = pd.DataFrame({ 'x': [[0, 1.1, 2, 8, 10], [0, 1.1, 3, 4, 10], [0, 1.1, 4, 9, 10]], 'y': [[0, 1.5, 2.5, 3.5, 4.5], [0, 100, 200, 300, 400], [0, 300, 500, 700, 900]] })
核心处理逻辑:
# 计算x列所有列表的公共元素集合 common_set = reduce(lambda a, b: set(a) & set(b), df['x']) # 按第一行x的顺序排序公共元素,保证输出顺序和原列表匹配 sorted_common = [v for v in df.iloc[0]['x'] if v in common_set] # 逐行过滤,保留公共元素对应的x、y值 def filter_row(row): keep_idx = [i for i, val in enumerate(row['x']) if val in common_set] return pd.Series([sorted_common, [row['y'][i] for i in keep_idx]], index=['xcmd', 'y']) df = df.apply(filter_row, axis=1)
运行后输出结果完全匹配预期:
xcmd y 0 [0, 1.1, 10] [0, 1.5, 4.5] 1 [0, 1.1, 10] [0, 100, 400] 2 [0, 1.1, 10] [0, 300, 900]
内容的提问来源于stack exchange,提问作者Mainland
相关产品推荐
相关产品推荐

