使用条件创建多列

时间:2018-12-20 08:55:51

标签: python python-3.x pandas

我有一个包含“ 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

1 个答案:

答案 0 :(得分:3)

创建一系列差异,比较不等于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