如何找到 pandas 数据框中所有对行之间的差,均值和? [英] How to find the difference, mean, sum between all pairs of rows in pandas dataframe?

查看:90
本文介绍了如何找到 pandas 数据框中所有对行之间的差,均值和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下熊猫DataFrame。

I have the following pandas DataFrame.

import pandas as pd
df = pd.read_csv('filename.csv')

print(df)

     dog      A         B           C
0     dog1    0.787575  0.159330    0.053095
1     dog10   0.770698  0.169487    0.059815
2     dog11   0.792689  0.152043    0.055268
3     dog12   0.785066  0.160361    0.054573
4     dog13   0.795455  0.150464    0.054081
5     dog14   0.794873  0.150700    0.054426
..    ....
8     dog19   0.811585  0.140207    0.048208
9     dog2    0.797202  0.152033    0.050765
10    dog20   0.801607  0.145137    0.053256
11    dog21   0.792689  0.152043    0.055268
    ....

我想找到所有行之间 A 的绝对差。如何做到这一点(牢记数据增长很快)?

I want to find the absolute difference of A between all rows. How does one do this (keeping in mind the data grows very quickly)?

配对数据的一种方法是尝试:

One way to "pair" the data is to try:

df1 = df.set_index("dog")

from itertools import combinations
cc = list(combinations(df,2))

out = pd.DataFrame([df1.loc[c,:].sum() for c in cc], index=cc)

但是,这只是求和。您如何进行多项操作?

However, this is only summing. How do you do multiple operations?

推荐答案

请考虑以下数据框:

import numpy as np
import pandas as pd

df = pd.DataFrame({'Dog': list('ABCDEFG'), 'A': range(7)})[['Dog', 'A']]
df

使用numpy的减去函数,然后取绝对值。

Use numpy's subtract.outer function then take the absolute value.

df1 = pd.DataFrame(np.abs(np.subtract.outer(df.A, df.A)), df.Dog, df.Dog)
df1

以获得组合元组的列表:

to get a list of combination tuples:

stacked = df1.stack()
pd.DataFrame({'Dogs': stacked.index.to_series(), 'Diff': stacked})[['Dogs', 'Diff']].reset_index(drop=True)

这篇关于如何找到 pandas 数据框中所有对行之间的差,均值和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆