gpt4 book ai didi

python - 创建具有条件的多列

转载 作者:行者123 更新时间:2023-11-30 22:02:11 25 4
gpt4 key购买 nike

我有一个包含“Rate”、“value1”、“value2”列的数据集。我想在每次汇率变化时生成新的列。每当速率发生变化时,将从第一行开始填充值。我附上了一个图像文件以供引用。我想生成“newvalue1”,“newvalue2”,“newvalue3”Example Image

    Rate  value1  value2
0 2 5 1
1 2 3 6
2 2 5 0
3 2 3 3
4 2 6 6
5 3 3 1
6 3 1 4
7 3 9 7
8 4 6 8
9 4 0 4
10 4 4 2
11 4 6 7
12 5 7 9
13 5 8 0

最佳答案

创建一系列差异,比较不等于0并添加累积和,然后在for循环中使用numpy.where创建新列

s = df['Rate'].diff().ne(0).cumsum()
for x in s.unique()[:-1]:
#python 3.6+
df[f'New{x}'] = np.where(s <= x, df['value1'], df['value2'])
#python bellow
#df['New{}'.format(x)] = np.where(s <= x, df['value1'], df['value2'])

print (df)
Rate value1 value2 New1 New2 New3
0 2 5 1 5 5 5
1 2 3 6 3 3 3
2 2 5 0 5 5 5
3 2 3 3 3 3 3
4 2 6 6 6 6 6
5 3 3 1 1 3 3
6 3 1 4 4 1 1
7 3 9 7 7 9 9
8 4 6 8 8 8 6
9 4 0 4 4 4 0
10 4 4 2 2 2 4
11 4 6 7 7 7 6
12 5 7 9 9 9 9
13 5 8 0 0 0 0

关于python - 创建具有条件的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865290/

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