Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Use Index as a variable for an equation in a DataFrame

I have the following code:

def linear_rank_selection(popRanked):   
selectionResults = []
n = len(popRanked)

df = pd.DataFrame(np.array(popRanked), columns=["A","B"])
df['Probability'] = 2*(n- df.index+1 )/(n*(n-1))*100

How can I use the index number, as a variable, to create the Probability column? Based on the probability formula whereas j is the index number.

question from:https://stackoverflow.com/questions/65869735/use-index-as-a-variable-for-an-equation-in-a-dataframe

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

1 Answer

0 votes
by (71.8m points)

I think the problem here is with RangeIndex when we try to do the division. Try convert index to numpy:

popRanked = [(100, 50), (215, 3) , (500,4)]
n = len(popRanked)
df = pd.DataFrame(np.array(popRanked), columns=["A","B"])
df['Probability'] = 2*(n- df.index.to_numpy()+1 )/(n*(n-1))*100

print(df)
     A   B  Probability
0  100  50   133.333333
1  215   3   100.000000
2  500   4    66.666667

We can also use df.index.values instead df.index.to_numpy()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...