Python&熊猫:如何进行条件计算

时间:2015-08-07 08:07:42

标签: python pandas

df['direction']是风的方向数,范围从1到16。我想将其转换为360-degree system#1方向为90#267.5,方向为顺时针方向。

我可以df['degree'] = 90-(df.direction-1)*22.5,但这会产生negative value,您可以看到下面的输出 ![enter image description here] 1

但我不知道如何在conditional使用df['degree']<0, then + 360。我怎么能这样做?

5 个答案:

答案 0 :(得分:3)

df['degree'] = df['degree'].apply(lambda x: x + 360 if x < 0 else x)

答案 1 :(得分:1)

如果我理解正确,那么您需要以下内容:

In [36]:

df = pd.DataFrame({'direction':np.random.randint(1,17,20)})
df
Out[36]:
    direction
0          13
1          12
2           4
3           5
4          16
5           6
6           3
7          16
8          12
9           2
10         14
11         13
12          8
13          9
14          8
15         12
16          9
17          2
18          7
19          8
In [37]:

df['degrees'] = (90 - (df['direction'] -1) * 22.5)
df.loc[df['degrees']<0,'degrees'] += 360.0
df
Out[37]:
    direction  degrees
0          13    180.0
1          12    202.5
2           4     22.5
3           5      0.0
4          16    112.5
5           6    337.5
6           3     45.0
7          16    112.5
8          12    202.5
9           2     67.5
10         14    157.5
11         13    180.0
12          8    292.5
13          9    270.0
14          8    292.5
15         12    202.5
16          9    270.0
17          2     67.5
18          7    315.0
19          8    292.5

答案 2 :(得分:1)

解决问题的简短方法是使用modulo。

df['degree'] = (90-(df.direction-1)*22.5)%360

答案 3 :(得分:1)

您可以使用.loc进行条件索引

df.loc[ df.degree < 0 , 'degree'] += 360

答案 4 :(得分:0)

使用df [度]&lt; 0作为条件声明:

df[degree] += (df[degree]<0) * 360