使用逗号作为'nan'从csv中读取带有pandas的字符串

时间:2016-12-06 15:26:58

标签: python csv pandas dataframe dataset

我尝试使用pandas读取数据框的我的csv文件如下所示:

Country Name    Country Code    Series Name                             Series Code
Afghanistan     AFG             Access to electricity (% of population) EG.ELC.ACCS.ZS
Albania         ALB             Life expectancy at birth, male (years)  SP.DYN.LE00.MA.IN

我用命令打开它:

df = pd.read_csv(file, skiprows=0, usecols=[2,3])

当它运行时:

for index, row in frame.iterrows():
    if row[1] == 'SP.DYN.LE00.MA.IN':
        print("Sample ", row[0])

我得到了输出:

Sample nan

有时它会正确读取“系列名称”列中的值,但有时不会,因为这个“nan”。 我应该怎么做才能使它经常以逗号的形式阅读“系列名称”?

感谢。

编辑:

我尝试用逗号清除文件数据,但它仍然不起作用:

def cleanCommasFromCSV(path_old, path_new):
    with open(path_old, "r", newline="") as infile, open(path_new, "w", newline="") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        writer.writerow(item.replace(",", "") for item in row)

0 个答案:

没有答案