将dataFrame解析为熊猫。
用户可以使用DataFrame.idxmax
获得最大值的索引(列)名称。
但是,如果该行中的所有值均为零(或等于等于),则默认情况下索引将返回第一列。
因此,一个过滤器如何过滤全零的或所有相等的值,以便不返回任何列名。
我正在使用pandas.DataFrame.idxmax
帮助文件。
但是,没有过滤器选项。
我相信人们可以使用loc[df['something']==value]
过滤熊猫,但是我不确定如何做到这一点。
import pandas as pd
myArr = {'column0':[1, 1, 0, 1, 1],
'column1':[1, 2, 0, 4, 5],
'column2':[100,200,0,400,500],
'column3':[1000,2000,0,4000,5000]}
df = pd.DataFrame(myArr)
#print(df)
m = df.idxmax(axis=1)
print(m)
实际结果:
0 column3
1 column3
2 column0
3 column3
4 column3
第二行中的值默认为第一列,因为该值为零(或等于)。
如何将其过滤掉?
答案 0 :(得分:0)
找出答案并添加以下内容:
[1]首先过滤零值。 [2]接下来,找到最大值。
# apply a filter for rows with zero's
print('apply zero filter:')
nz = df.loc[df['column0'] > 0]
print(nz)
# find the max values of the rest
print('get max values:')
m = nz.idxmax(axis=1)
print(m)
已过滤的列为:
column0 column1 column2 column3
0 1 1 100 1000
1 1 2 200 2000
3 1 4 400 4000
4 1 5 500 5000
最大列标题为:
0 column3
1 column3
3 column3
4 column3
答案 1 :(得分:0)
要检测不为零的相同值,下面的代码应该起作用:
import pandas as pd
myArr = {
'column0': [1, 1, 0, 1, 1, 5],
'column1': [1, 2, 0, 4, 5, 5],
'column2': [100, 200, 0, 400, 500, 5],
'column3': [1000, 2000, 0, 4000, 5000, 5],
}
m = (
pd.DataFrame(myArr)
.assign(
values_number=lambda x: x.apply(lambda s: len(pd.unique(s)), axis='columns')
)
.loc[lambda x: x['values_number'] > 1]
.drop(['values_number'], axis='columns')
.idxmax(axis=1)
)
print (m)
与values_number
关联的lambda函数计算给定行中唯一值的数量。
我还创建了具有相同值但不同零的最后一行。