[英]summing two columns in a dataframe
My df looks as follows:我的 df 如下所示:
Roll Name Age Physics English Maths
0 A1 Max 16 87 79 90
1 A2 Lisa 15 47 75 60
2 A3 Luna 17 83 49 95
3 A4 Ron 16 86 79 93
4 A5 Silvia 15 57 99 91
I'd like to add the columns Physics, English, and Maths and display the results in a separate column 'Grade'.我想添加物理、英语和数学列,并将结果显示在单独的“等级”列中。
I've tried the code:我试过代码:
df['Physics'] + df['English'] + df['Maths']
But it just concatenates.但它只是连接起来。 I am not taught about the lambda function yet.
我还没有听说过 lambda function。 How do I go about this?
我该如何 go 关于这个?
df['Grade'] = df['Physics'] + df['English'] + df['Maths']
it concatenates maybe your data is in **String**
just convert into float or integer.
它可能连接您的数据在
**String**
中,只需转换为float or integer.
Check Data Types First by using df.dtypes
首先使用
df.dtypes
检查数据类型
Try:尝试:
df["total"] = df[["Physics", "English", "Maths"]].sum(axis=1)
df
Check Below code, Its is possible you columns are in string format, belwo will solve that:检查下面的代码,您的列可能是字符串格式,下面将解决:
import pandas as pd
df = pd.DataFrame({"Physics":['1','2','3'],"English":['1','2','3'],"Maths":['1','2','3']})
df['Total'] = df['Physics'].astype('int') +df['English'].astype('int') +df['Maths'].astype('int')
df
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.