我有一列价格低于我想要在Python中的一个班轮列表理解中清理
Prices
15.90 EUR
17.80 EUR
15,80 EUR
26.10 EUR
44,10 EUR
3A'999,90,,,,,,,,
我的代码:
prices = df.Prices
prices = [re.findall('\d+.\d+',str(x).replace(',','.'))[0] for x in prices] # It works but not suitable for last price
prices = [x==re.findall('\d+.\d+',str(x).replace(',','.')) for x in prices if len(x)>0 else None] # Wrong syntax
我希望如果没有匹配则应添加None
并在正则表达式匹配时更正价格。我可以通过使用if else或尝试除了但我想使用一个衬垫很长的路要走。可能吗 ?
答案 0 :(得分:1)
In [35]: df
Out[35]:
Prices
0 15.90 EUR
1 17.80 EUR
2 15,80 EUR
3 26.10 EUR
4 44,10 EUR
5 3A'999,90
6 333
In [36]: df.dtypes
Out[36]:
Prices object
dtype: object
In [37]: df['Prices'] = pd.to_numeric(df.Prices.str.replace(',','.')
...: .str.extract(r'(\d+[\.,]{,1}?\d+?)',
...: expand=False),
...: errors='coerce')
In [38]: df
Out[38]:
Prices
0 15.9
1 17.8
2 15.8
3 26.1
4 44.1
5 999.9
6 333.0
In [39]: df.dtypes
Out[39]:
Prices float64
dtype: object
答案 1 :(得分:0)
更正语法
prices = [x==re.findall('\d+.\d+',str(x).replace(',','.')) if len(x)>0 else None for x in prices]