2016-12-07 58 views
1

我有我的数据的一个coluknn是:替换'?'与南或零

Power: 
0  130 
1  165 
2  150 
3  150 
4  ? 
5  198 
6  220 
7  215 
8  225 
9  ? 
10 170 

,我想更换每一个“?”与南或零。

我想:

data['Power'].str.replace('?', 0).astype(float) 
data['Power'].str.replace('^[^\d]*', '').astype(float) 
data['Power'].replace(r'\s+', np.nan, regex=True) 
data['Power'].convert_objects(convert_numeric=True) 
data['Power'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'') 

但这些作品!

有些产生错误could not convert string to float有些产生错误,但没有改变'?'。

+0

'data'变量是什么样的? –

+0

如果0是一个字符串,你的第一次尝试就会奏效。 –

回答

4

如果需要更换只有所有非数值到NaN使用to_numeric

data.Power = pd.to_numeric(data.Power, errors='coerce') 
print (data) 
    Power 
0 130.0 
1 165.0 
2 150.0 
3 150.0 
4  NaN 
5 198.0 
6 220.0 
7 215.0 
8 225.0 
9  NaN 
10 170.0 

如果需要0然后投加fillnaint

data.Power = pd.to_numeric(data.Power, errors='coerce').fillna(0).astype(int) 
print (data) 
    Power 
0  130 
1  165 
2  150 
3  150 
4  0 
5  198 
6  220 
7  215 
8  225 
9  0 
10 170 
1
# to replace with 0 
df.Power = df.Power.replace(to_replace='?', value = 0) 
# to replace with NaN 
import numpy as np 
df.Power = df.Power.replace(to_replace='?', value = np.nan) 
+0

帮我改进此答案?我以为我很好地回答了这个问题的标题 –

1

你也可以试试这个:

data['Power'].apply(lambda s: eval(str(s).replace('?', '0'))) 
1
import pandas as pd 

df = pd.DataFrame({ 
        'Power':[130,165,150,'?',198,220,215,225,'?',170] 
        }) 

df.where(df.Power != '?', 0) 

输出:

Power 
0 130 
1 165 
2 150 
3  0 
4 198 
5 220 
6 215 
7 225 
8  0 
9 170 

df.where(df.Power != '?', 'foo') 

输出

Power 
0 130 
1 165 
2 150 
3 foo 
4 198 
5 220 
6 215 
7 225 
8 foo 
9 170 

作品与几乎任何东西,它在它的快速的文档说。 The where() Method and Masking