gpt4 book ai didi

python - df[column] = apply(lambda row : row. sort_values()[1]) 行为奇怪

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:25 25 4
gpt4 key购买 nike

问题是:为什么 top_2_should 的值与 top_2_is 不同 - 或者换句话说 - 如果将 apply 函数分配给列,为什么它的结果是错误的?

编辑:因为我认为这个问题有点被误解,所以我创建了另一个例子。EDIT2:我使用Python 2.7.12::Anaconda 4.0.0(64位)::Pandas 0.18.0

import pandas as pd

d = {'one' : [1., 2., 3., 4.],
'two' : [4., 3., 2., 1.]}
df52 = pd.DataFrame(d)

top_1_should = df52.apply(lambda row: row.sort_values()[0], 1)
top_2_should = df52.apply(lambda row: row.sort_values()[1], 1)
df52['top_1_is'] = df52.apply(lambda row: row.sort_values()[0], 1)
df52['top_1_should'] = top_1_should
df52['top_2_is'] = df52.apply(lambda row: row.sort_values()[1], 1)
df52['top_2_should'] = top_2_should
print df52

one two top_1_is top_1_should top_2_is top_2_should
0 1.0 4.0 1.0 1.0 1.0 4.0
1 2.0 3.0 2.0 2.0 2.0 3.0
2 3.0 2.0 2.0 2.0 2.0 3.0
3 4.0 1.0 1.0 1.0 1.0 4.0

最好,一月

最佳答案

我认为你可以使用Series.sort_valuesvalues对于中断对齐行:

print (df52.apply(lambda row: row.sort_values().values, axis=1))
one two
0 1.0 4.0
1 2.0 3.0
2 2.0 3.0
3 1.0 4.0

或者:

print (pd.DataFrame(np.sort(df52.values), df52.index, df52.columns))
one two
0 1.0 4.0
1 2.0 3.0
2 2.0 3.0
3 1.0 4.0
<小时/>

如果使用print,您将获得排序的输出 - 如果之前添加新列,需要更改Series中所选行的位置,即DataFrame<中的列:

top_1_should = df52.apply(lambda row: row.sort_values()[0], 1)
top_2_should = df52.apply(lambda row: row.sort_values()[1], 1)
df52['top_1_is'] = df52.apply(lambda row: row.sort_values()[0], 1)
df52['top_1_should'] = top_1_should
df52['top_2_is'] = df52.apply(lambda row: row.sort_values()[1], 1)
df52['top_2_is'] = df52.apply(lambda row: print(row.sort_values()), 1)
one 1.0
top_1_is 1.0
top_1_should 1.0
top_2_is 1.0
two 4.0
Name: 0, dtype: float64
one 2.0
top_1_is 2.0
top_1_should 2.0
top_2_is 2.0
two 3.0
Name: 1, dtype: float64
two 2.0
top_1_is 2.0
top_1_should 2.0
top_2_is 2.0
one 3.0
Name: 2, dtype: float64
two 1.0
top_1_is 1.0
top_1_should 1.0
top_2_is 1.0
one 4.0
Name: 3, dtype: float64

关于python - df[column] = apply(lambda row : row. sort_values()[1]) 行为奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com