简体   繁体   English

如何替换或交换 python 中的所有值(最大和最小)?

[英]How to replace or swap all values (largest with smallest) in python?

I want to swap all the values of my data frame.Largest value must be replaced with smallest value (ie 7 with 1, 6 with 2, 5 with 3, 4 with 4, 3 with 5, and so on..我想交换我的数据框的所有值。必须用最小值替换最大值(即 7 与 1、6 与 2、5 与 3、4 与 4、3 与 5,等等。

import numpy as np
import pandas as pd
import io

data = '''
Values
6
1
3
7
5
2
4
1
4
7
2
5
'''
df = pd.read_csv(io.StringIO(data))

Trial审判

First I want to get all the unique values from my data.首先,我想从我的数据中获取所有唯一值。

df1=df.Values.unique()
print(df1)
[6 1 3 7 5 2 4]

I have sorted it in ascending order:我按升序对它进行了排序:

sorted1 = list(np.sort(df1))
print(sorted1)
[1, 2, 3, 4, 5, 6, 7]

Than I have reverse sorted the list:比我对列表进行反向排序:

rev_sorted = list(reversed(sorted1))
print(rev_sorted)
[7, 6, 5, 4, 3, 2, 1]

Now I need to replace the max.现在我需要更换最大值。 value with min.最小值value and so on in my main data set (df).我的主要数据集(df)中的值等等。 The old values can be replaced or a new column might be added.可以替换旧值或添加新列。

Expected Output :预期 Output

Values,New_Values
6,2
1,7
3,5
7,1
5,3
2,6
4,4
1,7
4,4
7,1
2,6
5,3

Here's a vectorized one -这是一个矢量化的 -

In [51]: m,n = np.unique(df['Values'], return_inverse=True)

In [52]: df['New_Values'] = m[n.max()-n]

In [53]: df
Out[53]: 
    Values  New_Values
0        6           2
1        1           7
2        3           5
3        7           1
4        5           3
5        2           6
6        4           4
7        1           7
8        4           4
9        7           1
10       2           6
11       5           3

Translating to pandas with pandas.factorize -使用 pandas.factorize 转换为pandas.factorize -

m,n = pd.factorize(df.Values, sort=True)
df['New_Values'] = n[m.max()-m]

Use Series.map by dictionary created by sorted and reverse sorting lists:通过排序和反向排序列表创建的dictionary使用Series.map

df['New'] = df['Values'].map(dict(zip(sorted1,rev_sorted)))
print (df)
    Values  New
0        6    2
1        1    7
2        3    5
3        7    1
4        5    3
5        2    6
6        4    4
7        1    7
8        4    4
9        7    1
10       2    6
11       5    3

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

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