gpt4 book ai didi

python - 如何根据同一行中另一列中的值向前填充列值

转载 作者:行者123 更新时间:2023-12-01 00:05:27 25 4
gpt4 key购买 nike

我想根据次数列转发填写金额列。例如第一个值是 2800000.0 ,我希望这个值被填充6次。

amount      times       
2800000.0 6
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
4750000.0 4
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0

期望的输出:

amount      times       
2800000.0 6
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
4750000.0 4
4750000.0 0
4750000.0 0
4750000.0 0
4750000.0 0
nan 0 0
nan 0 0

最佳答案

首先通过使用累积和测试非缺失值来创建组并传递给 GroupBy.apply带有 lambda 函数 Series.ffill每组的第一个值受到限制:

#if necessary convert strings t onumeric and NaNs
#df['amount'] = pd.to_numeric(df['amount'], errors='coerce')

print (df['amount'].dtype)
float64

g = df['amount'].notna().cumsum()

f = lambda x: x['amount'].ffill(limit=x['times'].iat[0])
df['amount'] = df.groupby(g, group_keys=False).apply(f)
print (df)
amount times
0 2800000.0 6
1 2800000.0 0
2 2800000.0 0
3 2800000.0 0
4 2800000.0 0
5 2800000.0 0
6 2800000.0 0
7 4750000.0 4
8 4750000.0 0
9 4750000.0 0
10 4750000.0 0
11 4750000.0 0
12 NaN 0
13 NaN 0

关于python - 如何根据同一行中另一列中的值向前填充列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com