改变字符串数据帧中的nans

时间:2018-04-06 13:12:36

标签: python pandas

我从cvs文件中读取。我的数据框包含真正浮动的字符串。还有NaN值。
基本上我想在平均值中转换NaN并在浮点数中转换字符串。
有些方法可以帮助像fillna替换nan值,因为它不能得到平均值(原因值是字符串)。
还有一个float()方法,但如果它应用于NaN,它将给出0,这对我不利。
是否有任何好的决定用均值替换NaN值并将字符串转换为浮点数?
数据帧示例:

1   9,5  50,6  45,75962845  2,6  6,5   11  8,9  NaN  
2  10,5  59,9  74,44538987    0  4,5  8,9  NaN  NaN
3  20,1  37,7          NaN  0,8  2,5  9,7  6,7  4,2  
4  10,7  45,2   10,9710853  0,4  3,1  6,9  5,5  4,7    
5  13,2  39,9   9,23393302    0  5,8  9,2  7,4  4,3    

P.S As A. Leistra建议我使用

for col in df.columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
    df[col].fillna(df[col].mean())
带有to_numeric

errors='coerce'会创建大量新的NaN。 errors='ignore'参数似乎不错,但在TypeError: Can't convert 'int' object to str implicitly

行上提供了df[col].fillna(df[col].mean())

P.S.2正如piRSquared建议我尝试在read_csv函数中添加decimal=','。但它仍然给出了相同的错误TypeError: Can't convert 'int' object to str implicitly

2 个答案:

答案 0 :(得分:3)

如果您使用decimal=',',则应使用pd.read_csv参数读取数据。否则,如果您坚持使用此数据框,则可以将其转储到csv并重试。

pd.read_csv(pd.io.common.StringIO(df.to_csv(index=False)), decimal=',')

   0     1     2          3    4    5     6    7    8
0  1   9.5  50.6  45.759628  2.6  6.5  11.0  8.9  NaN
1  2  10.5  59.9  74.445390  0.0  4.5   8.9  NaN  NaN
2  3  20.1  37.7        NaN  0.8  2.5   9.7  6.7  4.2
3  4  10.7  45.2  10.971085  0.4  3.1   6.9  5.5  4.7
4  5  13.2  39.9   9.233933  0.0  5.8   9.2  7.4  4.3

填写缺失数据变得容易。

d = pd.read_csv(pd.io.common.StringIO(df.to_csv(index=False)), decimal=',')
d.fillna(d.mean())

   0     1     2          3    4    5     6      7    8
0  1   9.5  50.6  45.759628  2.6  6.5  11.0  8.900  4.4
1  2  10.5  59.9  74.445390  0.0  4.5   8.9  7.125  4.4
2  3  20.1  37.7  35.102509  0.8  2.5   9.7  6.700  4.2
3  4  10.7  45.2  10.971085  0.4  3.1   6.9  5.500  4.7
4  5  13.2  39.9   9.233933  0.0  5.8   9.2  7.400  4.3

答案 1 :(得分:1)

首先,您需要使用to_numeric将字符串转换为浮点数:

for col in df.columns:
   df[col] = pd.to_numeric(df[col], errors='coerce')

(使用'强制'用NaN替换不可转换的值,这就是你想要的)。然后,您就可以使用fillna

df.fillna(df.mean())
相关问题