pandas pd.read_csv 有没有办法用其他字符替换 NaN 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47286547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:45:59  来源:igfitidea点击:

Is there a way in pd.read_csv to replace NaN value with other character?

pythonpandascsv

提问by Will Shaw

I have some data in csv file. Because it is collected from machine,all lines should be number but some NaN values exists in some lines.And the machine can auto replace these NaN values with a string '-'.

我在 csv 文件中有一些数据。因为它是从机器收集的,所以所有行都应该是数字,但某些行中存在一些 NaN 值。并且机器可以自动将这些 NaN 值替换为字符串“-”。

My question is how to set params of pd.read_csv()to auto replace '-'values with zero from csv file?

我的问题是如何设置pd.read_csv() 的参数以自动用 csv 文件中的零替换“-”值?

回答by shivsn

while reading the csvfile you can use the parameter na_values:

在读取csv文件时,您可以使用参数na_values

df = pd.read_csv('file.csv',na_values='-')

Edit: you can then convert nan to 0 by:

编辑:然后您可以通过以下方式将 nan 转换为 0:

df.fillna(0,1,inplace=True)

回答by Saghe Achraf

You can try something like this :

你可以尝试这样的事情:

import pandas

df = pandas.read_csv('somefile.txt')

df = df.fillna(0)

Hope that'll help !

希望这会有所帮助!