简体   繁体   English

列的最大值和最小值之间的差异

[英]Difference between max and min value of columns

I have a pandas dataframe with 2000+ columns.我有一个 pandas dataframe 与 2000+ 列。 All the columns have numeric values.所有列都有数值。 I want to find the difference between minimum and maximum values of each column.我想找到每列的最小值和最大值之间的差异。 And then I want to filter top 10 columns having biggest differences.然后我想过滤出差异最大的前 10 列。

Col1 Col2 Col3 ..... Col2500
 4     1    3  .....    6
 7     5   10  .....    17
 1    22    4  .....    2

I tried a few options, but none worked.我尝试了几个选项,但没有一个有效。 Please suggest a solution.请提出解决方案。

This will give you the result in Series :这将为您提供Series的结果:

df.T.apply(lambda x: x.max() - x.min(), axis=1).nlargest(10)

Example:例子:

df

   Col1  Col2  Col3  Col2500
0     4     1     3        6
1     7     5    10       17
2     1    22     4        2

df.T.apply(lambda x: x.max() - x.min(), axis=1).nlargest(3)

Col2       21
Col2500    15
Col3        7
dtype: int64

Or just:要不就:

(df.max() - df.min()).nlargest(10)

Here is my solution这是我的解决方案

>>> data = {'Col1':[4,7,1],'Col2':[1,5,22], 'Col3':[3,10,4], 'Col2500':[6,17,2]}
>>> df = pd.DataFrame(data)
>>> df
   Col1  Col2  Col3  Col2500
0     4     1     3        6
1     7     5    10       17
2     1    22     4        2
>>> diff = df.max() - df.min()
>>> diff
Col1        6
Col2       21
Col3        7
Col2500    15
>>> pd.DataFrame(diff).sort_values(by=0, ascending=False)
          0
Col2     21
Col2500  15
Col3      7
Col1      6

Hope this helps !希望这可以帮助 !

diff = df.max() - df.min()

diff.sort_values()

Example:例子:

>>> df.values
array([[  0,  12,  42],
       [  1,  13,  21],
       [ 12,   1,  30],
       [  3,  45, -39],
       [  4,   1,  38]])

>>> diff = df.max() - df.min()
>>>
>>> diff.sort_values(ascending=False)
T3    81
T2    44
T1    12
dtype: int64
>>> diff.sort_values()
T1    12
T2    44
T3    81
dtype: int64
>>>
import pandas as pd
import numpy as np

#sample data
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

#transposing data so columns are now rows and column names are indices
df = df.transpose()

#Calculation of Max - Min per row
df['dif'] = df.max(axis=1) - df.min(axis = 1)

#Number of results at the end (10 in your case)
TOP_N = 2

#Resetting the index to get column names and sorting by difference high to low
result = df.reset_index().rename(columns={'index':'ColumnName'})[['ColumnName','dif']].sort_values(by=['dif'],ascending=[False]).head(TOP_N)

print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM