简体   繁体   English

将 dataframe 列值除以该列的总和

[英]Divide dataframe column value by the total of the column

My question might be too easy for many of you but since i'm a beginner with Python..我的问题对你们中的许多人来说可能太容易了,但因为我是 Python 的初学者。

I want to have the % by value of a column containing 3 different possible values (1,0,-1) but by excluding one of the values in the column (which is -1).我想获得包含 3 个不同可能值(1,0,-1)但排除列中的一个值(即-1)的列的值百分比。

I did this: (df['col_name']).sum()/len(df.col_name)我这样做了: (df['col_name']).sum()/len(df.col_name)

However it also counts the -1 in it, while i just want to have the % of the value 1/total sum, but without -1 in the total sum.然而,它也计算其中的 -1,而我只想获得值 1/总和的百分比,但总和中没有 -1。

Thank you for your help.谢谢您的帮助。

For exclude values replace -1 to missing values:对于排除值,将-1替换为缺失值:

df['col_name'].replace(-1, np.nan).sum()/len(df.col_name) 

Or filter out -1 values if need count lengths of filtered Series:或者如果需要计算过滤系列的长度,则过滤掉-1值:

np.random.seed(123)
df = pd.DataFrame({'col_name':np.random.choice([0,1,-1], size=10)})

print (df)
   col_name
0        -1
1         1
2        -1
3        -1
4         0
5        -1
6        -1
7         1
8        -1
9         1

s = df.loc[df['col_name'] != -1, 'col_name']
print (s)
1    1
4    0
7    1
9    1
Name: col_name, dtype: int32

print (s.sum()/len(s))
0.75

print (s.mean())
0.75

Assuming you have this dataframe假设你有这个 dataframe

df = pd.DataFrame({
    'col_name': [1,1,0,-1,-1,1,0]
    })

    col_name
0   1
1   1
2   0
3   -1
4   -1
5   1
6   0

You would like to count the number of 1's divided by total numbers without -1's, which is 3 out of 5, correct?您想计算 1 的数量除以没有 -1 的总数,即 5 个中的 3 个,对吗?

numerator = sum(df['col_name'].apply(lambda x: 1 if x==1 else 0))
denominator = sum(df['col_name'].apply(lambda x: 0 if x==-1 else 1))
print(numerator/denominator)

Output 0.6 Output 0.6

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

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