Python Pandas替换错误的

时间:2016-07-19 07:44:53

标签: python-3.x pandas

我的DataFrame看起来像这样:

Date  WaterTemp
1       21.4
2       20.8
3       20.4
4       20.0
5       19.9
6       20.5
7       20.8
8       21.4
9       21.7
10       22.1
11       21.9
12       21.3
13       21.5
14       21.6
15       21.4
16       21.7
17       22.4
18       22.4
19       22.5
20       22.6
21       23.1
22       23.8
23       23.8
24       23.1
25       22.9
26       23.4
27       23.6
28       23.4
29       24.1
30       24.6
31       24.1
32       23.9
33       23.6
34       23.3
35       23.2
36       23.4
37       23.1
38       22.3
39       22.4
40       22.4

我想像这样替换WaterTemp的值:

wt = df['WaterTemp']

for line in wt:
        if line <= 11.5:
            WaterTemp = WaterTemp.replace(line, "LWT")
        elif line >= 22.5:
            WaterTemp = WaterTemp.replace(line, "HWT")
        else:
            WaterTemp = WaterTemp.replace(line, "")

但结果为.csv看起来像这样:

1,
2,
3,
4,
5,
6,
LWT,
LWT,
LWT,
LWT,HWT
LWT,HWT
,
,
,
,
,
,HWT
,HWT
,HWT
,HWT
,HWT
HWT,HWT
HWT,HWT
HWT,HWT
HWT,HWT
HWT,HWT
HWT,HWT
HWT,HWT
29,HWT
30,HWT
31,HWT
32,HWT
33,HWT
34,HWT
35,HWT
36,HWT
37,HWT
38,HWT
39,HWT
40,HWT

因此它将Date值从7更改为28.

我希望你能尽快帮助我。

3 个答案:

答案 0 :(得分:2)

这有点棘手,因为我通常会建议在loc中使用多个语句,但是一旦将行数设置为str,就会引入混合dtypes而你无法比较{{1}与str一起使用。无论如何,你可以使用嵌套的float语句实现这一点:

np.where

答案 1 :(得分:1)

我会使用Embedded Content Contains Swift Code

pd.cut
df.WaterTemp = pd.cut(df.WaterTemp,
                      [0, 11.5, 22.5, 100],
                      labels=['LWT', '', 'HWT'])

答案 2 :(得分:0)

如果要添加包含数据点的新列,可以使用:

import pandas as pd

df = pd.read_csv(r"C:\Users\ReddyAl\Documents\water temp.txt", sep=' ')

df['WaterTempClassification'] = 'Normal'
df.loc[df['WaterTemp'] <=11.2, 'WaterTempClassification'] = 'LWT'
df.loc[df['WaterTemp'] >=22.5, 'WaterTempClassification'] = 'HWT'

输出:

   Date WaterTemp   WaterTempClassification
0   1   21.4    Normal
1   2   20.8    Normal
2   3   20.4    Normal
3   4   20.0    Normal
4   5   19.9    Normal
5   6   20.5    Normal
6   7   20.8    Normal
7   8   21.4    Normal
8   9   21.7    Normal
9   10  22.1    Normal
10  11  21.9    Normal
11  12  21.3    Normal
12  13  21.5    Normal
13  14  21.6    Normal
14  15  21.4    Normal
15  16  21.7    Normal
16  17  22.4    Normal
17  18  22.4    Normal
18  19  22.5    HWT
19  20  22.6    HWT
20  21  23.1    HWT
21  22  23.8    HWT
22  23  23.8    HWT
23  24  23.1    HWT
24  25  22.9    HWT
25  26  23.4    HWT
26  27  23.6    HWT
27  28  23.4    HWT
28  29  24.1    HWT
29  30  24.6    HWT
30  31  24.1    HWT
31  32  23.9    HWT
32  33  23.6    HWT
33  34  23.3    HWT
34  35  23.2    HWT
35  36  23.4    HWT
36  37  23.1    HWT
37  38  22.3    Normal
38  39  22.4    Normal
39  40  22.4    Normal