【问题标题】:Python write edited NaNs in variable to .csvPython将变量中编辑的NaN写入.csv
【发布时间】:2016-12-30 01:20:27
【问题描述】:

我正在尝试将 .csv 中的 NULL 值转换为 NaN,然后使用这些编辑保存文件。下面代码中的f 在数据中的正确位置具有NaN 值。但是,我无法将其保存为 .csv。错误打印在代码下方。

#take .csv with NULL and replaces with NaN - write numerical and NaN values to .csv

import csv
import numpy as np
import pandas

f = pandas.read_csv('C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - Copy.csv')#convert file to variable so it can be edited
outfile = open('C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - NaN1.csv','wb')#create empty file to write to
writer = csv.writer(outfile)#writer will write when given the data to write below
result = f[f is 'NULL'] = np.nan

writer.writerows(f)

错误:

 Traceback (most recent call last):
  File "C:/Users/mmso2/Google Drive/MABL Wind/_Semester 2 2016/_PGR Training/CENTA/MATLAB/In class ex/SAR_data/gg_nan.py", line 12, in <module>
    writer.writerows(f)
_csv.Error: sequence expected

【问题讨论】:

标签: python python-2.7 csv nan


【解决方案1】:

我只是在学习 Python,但您可以在读取文件时替换 NULL 值,例如:

file = pd.read_csv('filename.csv', na_values=['NULL'])

甚至为每一列制作一个标记值字典,例如:

sentinels = {'column1':['Na', 'empty field'], 'somecolumn':['othervalues']}

file = pd.read_csv('filename.csv', na_values=sentinels)

【讨论】:

    【解决方案2】:

    csv.writer.writerows() 需要一个序列序列(行对象序列),而 pandas.DataFrame 不是,因为它在迭代时返回一个列名序列:

    In [23]: df = pd.DataFrame({'A': range(10)})
    
    In [24]: for x in df: 
        print(x)
       ....:     
    A
    

    这可能会让您无言以对,因为字符串序列实际上是序列序列,因此您最终会得到一个 CSV 文件,其中包含由列名字母组成的行。在您的情况下,由于您尝试替换“NULL”字符串的方式失败,最终添加了带有标签False(布尔值)的列。

    要遍历行元组,您可以使用 DataFrame.itertuples():

    In [27]: for x in df.itertuples(index=False):
        print(x)
       ....:     
    (0,)
    (1,)
    (2,)
    ...
    

    不过,最简单的方法是简单地使用 DataFrame.to_csv():

    filename = 'C:\Users\mmso2\Google Drive\MABL Wind\_Semester 2 2016\Wind Farm Info\DataB\DataB - NaN1.csv'
    f.to_csv(filename, na_rep='NaN')  # default representation for nans is ''
    

    请注意,要替换 'NULL' 值,您必须使用相等运算符而不是标识运算符 is

    f[f == 'NULL'] = np.nan
    

    使用标识将有效地添加一个标记为 False 的新列,所有值都设置为 nan:

    In [42]: df = pd.DataFrame({'A': ['NULL', 1] * 10})
    
    In [43]: df[df is 'NULL'] = float('nan')
    
    In [44]: df
    Out[44]: 
           A  False
    0   NULL    NaN
    1      1    NaN
    2   NULL    NaN
    3      1    NaN
    ...
    

    因为f is 'NULL' 的计算结果为False 而不是新的DataFrame

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多