Python 使用条件创建多列
我有一个列为“Rate”、“value1”、“value2”的数据集。我希望在每次速率更改时生成新列。无论何时速率更改,都将从第一行填充值。我附上了一个图像文件作为参考。我想生成“newvalue1”、“newvalue2”、“newvalue3”Python 使用条件创建多列,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个列为“Rate”、“value1”、“value2”的数据集。我希望在每次速率更改时生成新列。无论何时速率更改,都将从第一行填充值。我附上了一个图像文件作为参考。我想生成“newvalue1”、“newvalue2”、“newvalue3” 创建一系列差异,比较不相等的0并添加累积和,然后在for循环中使用创建新列 s=df['Rate'].diff().ne(0).cumsum() 对于s.unique()中的x[:-1]: #python 3.6+ df[f'New{x}']=np.
创建一系列差异,比较不相等的
0
并添加累积和,然后在for循环中使用创建新列
s=df['Rate'].diff().ne(0).cumsum()
对于s.unique()中的x[:-1]:
#python 3.6+
df[f'New{x}']=np.where(s
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
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