[英]How can I sum the values in one column based on the floor'd value of another column in pandas?
[英]Pandas DataFrame: Simple assignment - the floor of the difference of two column values to another column value, loop does not work
您将如何在 Pandas 中执行以下操作?
import math
for index, row in data.iterrows():
if row["year"] == 0:
row["year"] = math.floor((row["death"] - row["birth"])/2)
这个循环不起作用,但我想做的是,如果列年的值为 0,则将差异的下限除以死亡和出生列的 2 分配给列年。我知道你应该避免在 Pandas 中循环这可能有一个简单的解决方案,但我现在无法弄清楚。
使用numpy.where
:
import numpy as np
df['newcol'] = np.where(df['year'] == 0, math.floor((df['death'] - df['birth'])/2), df['year'])
这本质上是:
np.where(condition, if True then, if False then)
切片loc
:
df.loc[df['year'] == 0, 'year'] = np.floor((df.loc[df['year'] == 0, 'death'] - df.loc[df['year'] == 0, 'birth']) / 2)
也许是一个更具可读性的解决方案:
mask = df['year'] == 0
df.loc[mask, 'year'] = np.floor((df.loc[mask, 'death'] - df.loc[mask, 'birth']) / 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.