![](/img/trans.png)
[英]How to compare the values of each row with all the others in a DataFrame?
[英]how to compare all values for each row in a dataframe in python
大家早上好,我的问题很简单:
给定这样的 dataframe:
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
print(df)
我想为每一行检索最大值并将其与所有其他行进行比较。 如果差异大于 10,则创建另一个包含字符串“yes”或“not”的列
a b c
0 1 8 2
1 2 18 24
2 3 27 6
3 4 20 16
4 5 33 20
5 6 49 52
我期待这样的结果:
a b c res
0 1 8 2 not
1 2 18 24 not
2 3 27 6 yes
3 4 20 16 not
4 5 33 20 yes
5 6 49 52 not
非常感谢。
我想,下面的代码可以提供帮助:
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
def find(x):
if x > 10:
return "yes"
else:
return "not"
df["diff"] = df.max(axis=1) - df.apply(lambda row: row.nlargest(2).values[-1],axis=1)
df["res"] = df["diff"].apply(find)
df.drop(columns="diff", axis=0, inplace=True)
这应该可以解决问题。
大约是这里提供的其他答案的两倍到十倍
导入 pandas 作为 pd
df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
df["res"] = df.apply(lambda row: "yes" if all(row.apply(lambda val: max(row) - val > 10 or val == max(row))) else "not", axis=1)
print(df)
结果
a b c res
0 1 8 2 not
1 2 18 24 not
2 3 27 6 yes
3 4 20 16 not
4 5 33 20 yes
5 6 49 52 not
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6],
'b': [8, 18, 27, 20, 33, 49],
'c': [2, 24, 6, 16, 20, 52]})
def _max(row):
first, second = row.nlargest(2)
if first - second > 10:
return True
else:
return False
df["res"] = df.apply(_max, axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.