需要剥离字母的CSV列编号数据-熊猫



我正在开发一个.csv,它的列中的数字数据包括字母。我想去掉字母,这样列就可以是浮点或整数

我尝试过以下几种:

  • 使用循环/def过程剥离字符串数据的对象列;MPG";列,只留下数值。

  • 它应该打印列的名称,其中至少有一个条目以字符"mpg"结尾

在JUPYTER NOTEBOOK细胞中编码:

步骤1:

MPG_cols = []
for colname in df.columns[df.dtypes == 'object']:  
if df[colname].str.endswith('mpg').any(): 
MPG_cols.append(colname)
print(MPG_cols)
  • 使用.str,这样我就可以使用逐元素的字符串方法
  • 只想考虑字符串列

这给了我输出:

【权力】#到目前为止很好

步骤2:

#define the value to be removed using loop
def remove_mpg(pow_val):
"""For each value, take the number before the 'mpg'
unless it is not a string value. This will only happen
for NaNs so in that case we just return NaN.
"""
if isinstance(pow_val, str):
i=pow_val.replace('mpg', '') 
return float(pow_val.split(' ')[0]) 
else:
return np.nan
position_cols = ['Vehicle_type'] 
for colname in MPG_cols:
df[colname] = df[colname].apply(remove_mpg)
df[Power_cols].head() 

我得到的错误:


ValueError                                Traceback (most recent call last)
<ipython-input-37-45b7f6d40dea> in <module>
15 
16 for colname in MPG_cols:
---> 17     df[colname] = df[colname].apply(remove_mpg)
18 
19 df[MPG_cols].head()
~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/series.py in        apply(self, func, convert_dtype, args, **kwds)
3846             else:
3847                 values = self.astype(object).values
-> 3848                 mapped = lib.map_infer(values, f,     convert=convert_dtype)
3849 
3850         if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-37-45b7f6d40dea> in remove_mpg(pow_val)
8     if isinstance(pow_val, str):
9         i=pow_val.replace('mpg', '')
---> 10         return float(pow_val.split(' ')[0])
11     else:
12                     return np.nan
ValueError: could not convert string to float: 'null'

我将类似的代码应用于另一个专栏,它在那个专栏上起了作用,但在这里没有。

任何指导都将不胜感激。

最佳,

我认为您需要重新访问函数remove_mpg的逻辑,可以通过以下方式进行调整:

import re
import numpy as np
def get_me_float(pow_val):
my_numbers = re.findall(r"(d+.*d+)mpg", pow_val)
if len(my_numbers) > 0 :
return float(my_numbers[0])
else:
return np.nan

例如需要测试功能。

my_pow_val=['34mpg','34.6mpg','0mpg','mpg','anything']
for each_pow in my_pow_val:
print(get_me_float(each_pow))

输出:

34.0
34.6
nan
nan

nan

这将起作用,

import pandas as pd
pd.to_numeric(pd.Series(['$2', '3#', '1mpg']).str.replace('[^0-9]', '', regex=True))

0 2
1 3
2 1
数据类型:int64

对于完整的解决方案,

for i in range(df.shape[1]):
if(df.iloc[:,i].dtype == 'object'):
df.iloc[:,i] = pd.to_numeric(df.iloc[:,i].str.replace('[^0-9]', '', regex=True))
df.dtypes

选择不更改的列

for i in range(df.shape[1]):
# 'colA', 'colB' are columns which should remain same.
if((df.iloc[:,i].dtype == 'object') & df.column[i] not in ['colA','colB']):
df.iloc[:,i] = pd.to_numeric(df.iloc[:,i].str.replace('[^0-9]', '', regex=True))
df.dtypes

加载csv文件时,为什么不将converters参数用于read_csv函数来去除多余的字符?

def strip_mpg(s):
return float(s.rstrip(' mpg'))
df = read_csv(..., converters={'Power':strip_mpg}, ...)

最新更新