Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

python - pandas rank function 2 columns for high and low values

Here's some code to make up a pandas dataframe with 2 columns one called data and the other called hours. The data column is random int from -150 to 250. And the hours column is random floats from .5 to 15.5.

import random
import numpy as np
import pandas as pd

data = np.random.randint(-150,250,size=200)
df = pd.DataFrame(data, columns=['Data'])


#generate random floats for df2
randomFloatList = []
# Set a length of the list to length of pandas df1
for i in range(0, len(df)):
    # any random float between 5.50 to 50.50
    x = round(random.uniform(0.50, 15.50), 2)
    randomFloatList.append(x)

df2 = pd.DataFrame(randomFloatList,columns=['hours'])


combined = df.join(df2)
print(combined)

Returns:

     Data  hours
0      93   9.66
1      85  14.76
2     -82  12.55
3     -44   2.40
4      -1  13.86

Can Pandas rank function reorganize a dataframe based on the highest values in one column (data) and lowest values in a different column (hours) with rows in the dataset being preserved? Hopefully this makes sense...

If I use print(combined.rank(axis='columns'))

This returns something unwanted, I cant quite figure out if this is possible with the pandas rank or not.

     Data  hours
0     2.0    1.0
1     2.0    1.0
2     1.0    2.0
3     1.0    2.0
4     1.0    2.0

Any tips greatly appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

combined['hours_rank'] = combined['hours'].rank(ascending=1)
combined['Data_rank'] = combined['Data'].rank(ascending=1)

In Data
Data hours
0 174 0.89
1 226 7.41
2 -90 13.79
3 148 3.02

Out Data
Data hours hours_rank Data_rank
0 174 0.89 1.0 3.0
1 226 7.41 3.0 4.0
2 -90 13.79 4.0 1.0
3 148 3.02 2.0 2.0
enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...