[英]In a pandas dataframe, how can I filter the rows based on a column value, do calculation and assign the result to a new column?
例如,我有四个人的 dataframe,分为 A 组和 B 组。现在我想过滤掉 B 组,将他们的 Point 分成两半,并将结果分配给名为“Point_new”的新列。
我正在使用如下代码
import pandas as pd
data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
'Group':['A', 'B', 'B', 'A'],
'Point':[20, 21, 19, 18]}
df = pd.DataFrame(data)
df['Point_new'] = ''
df[df['Group']=='B']['Point_new'] = df[df['Group']=='B']['Point'] / 2
从上述代码的 output 来看,Point_new 列没有填充计算结果。 我想知道为什么会这样,我怎么能正确地做到这一点。
你可以这样做,关键是使用loc -
import pandas as pd
data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
'Group':['A', 'B', 'B', 'A'],
'Point':[20, 21, 19, 18]}
df = pd.DataFrame(data)
df.loc[(df['Group'] == 'B'),'Point_new'] = df.loc[df['Group']=='B','Point'] / 2
print(df)
Name Group Point Point_new
0 Tom A 20 NaN
1 Nick B 21 10.5
2 Krish B 19 9.5
3 Jack A 18 NaN
这是因为您试图在 DataFrame 的切片上设置一个值。 在此处查看更多信息: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
尝试这个:
df.loc[df['Group']=='B', 'Point_new'] = df[df['Group']=='B']['Point'] / 2
产生:
姓名 | 团体 | 观点 | Point_new | |
---|---|---|---|---|
0 | 汤姆 | 一个 | 20 | |
1 | 缺口 | 乙 | 21 | 10.5 |
2 | 克里什 | 乙 | 19 | 9.5 |
3 | 杰克 | 一个 | 18 |
你可以试试:
df = df.assign(Point_New = df[df.Group.eq('B')].Point.div(2))
Name Group Point Point_New
0 Tom A 20 NaN
1 Nick B 21 10.5
2 Krish B 19 9.5
3 Jack A 18 NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.