Python 替换'';是Nan还是零
我有一个coluknn我的数据是:Python 替换'';是Nan还是零,python,pandas,Python,Pandas,我有一个coluknn我的数据是: Power: 0 130 1 165 2 150 3 150 4 ? 5 198 6 220 7 215 8 225 9 ? 10 170 我想用Nan或零替换每个“?” 我试过: data['Power'].str.replace('?', 0).astype(float) data['Power'].str.replace('^[^\d]*', '').astype(f
Power:
0 130
1 165
2 150
3 150
4 ?
5 198
6 220
7 215
8 225
9 ?
10 170
我想用Nan或零替换每个“?”
我试过:
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'')
但这些都不管用
有些产生错误
无法将字符串转换为浮点值
,有些没有产生任何错误,但没有更改“?”。您也可以尝试以下方法:
# 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)
data['Power'].apply(lambda s: eval(str(s).replace('?', '0')))
您也可以尝试以下方法:
data['Power'].apply(lambda s: eval(str(s).replace('?', '0')))
如果需要,仅将所有非数值替换为
NaN
使用:
如果需要0
,则使用cast添加到int
:
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
如果需要,仅将所有非数值替换为
NaN
使用:
如果需要0
,则使用cast添加到int
:
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
输出:
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
几乎任何东西都能用,而且文档中说它很快。
输出:
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
几乎任何东西都能用,而且文档中说它很快。
数据变量<代码>是什么样子的?如果0是一个字符串,您的第一次尝试将有效。数据变量<代码>是什么样子的?如果0是一个字符串,您的第一次尝试将有效。请帮助我改进此答案?我想我已经回答了问题的标题了。你能帮我改进这个答案吗?我想我很好地回答了问题的标题