Pandas透视表条件过滤报错:带换行字符串首行数值比较问题
问题解决方法
错误原因
df1中存储的col7值均为带换行符的字符串类型,无法直接与整数做数值比较,同时排名逻辑也无法基于字符串正确计算。仅需要提取每个字符串第一行的数值用于条件判断,筛选时保留原始字符串值即可。
解决代码
import pandas as pd import numpy as np df = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'col2': ['test1', 'test1', 'test1', 'test1', 'test2', 'test2', 'test2', 'test2', 'test3', 'test3', 'test3', 'test3', 'test4', 'test5', 'test1', 'test1'], 'col3': ['t1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1', 't1'], 'col4': ['input1', 'input2', 'input3', 'input4', 'input1', 'input2', 'input3', 'input4', 'input1', 'input2', 'input3', 'input5', 'input2', 'input6', 'input1', 'input1'], 'col5': ['result1', 'result2', 'result3', 'result4', 'result1', 'result2', 'result3', 'result4', 'result1', 'result2', 'result3', 'result4', 'result2', 'result1', 'result2', 'result6'], 'col6': [10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 50, 20, 100, 10, 10], 'col7': ['100.2\n11','101.2\n21','102.3\n34','101.4\n41','100.0\n10','103.0\n20.6','104.0\n31.2','105.0\n42','102.0\n10.2', '87.0\n15','107.0\n32.1','110.2\n61.2','120.0\n22.4','88.0\n90','106.2\n16.2','101.1\n10.1']}) df1=df.pivot_table(values = 'col7', index = ['col4', 'col5', 'col6'], columns = ['col2'], aggfunc = 'max') # 构造临时数值表,仅用于条件判断 temp_numeric = df1.applymap(lambda x: float(x.split('\n')[0]) if pd.notna(x) else x) # 所有条件基于临时数值表计算,筛选原始df1 cond1 = (temp_numeric.groupby(level='col4').rank(ascending=False) == 1.).any(axis=1) cond2 = (temp_numeric >= 105).any(axis=1) df2 = df1[cond1 & cond2] print(df2)
运行上述代码输出结果和你预期的完全一致。
内容的提问来源于stack exchange,提问作者buggsbunny4
相关产品推荐
相关产品推荐

