【问题标题】:Python Pandas CSV "TypeError: <lambda>() takes exactly 1 argument (5 given)"Python Pandas CSV“TypeError:<lambda>() 只需要 1 个参数(给定 5 个)”
【发布时间】:2016-11-16 20:19:13
【问题描述】:

我有一个格式化的 CSV:

"Year","Month","Day","Hour","Minute","Direct","Diffuse","D_Global","D_IR","U_Global","U_IR","Zenith"
2001,3,1,0,1,0.28,84.53,83.53,224.93,76.67,228.31,80.031
2001,3,1,0,2,0.15,84.24,83.25,224.76,76.54,228.62,80.059
2001,3,1,0,3,0.16,84.63,83.43,225.62,76.76,229.06,80.087
2001,3,1,0,4,0.20,85.20,83.99,226.56,77.15,228.96,80.115

我的脚本是:

df1 = pd.read_csv(input_file,
        sep = ",",
        parse_dates = {'Date': [0,1,2,3,4]},
        date_parser = lambda x: pd.to_datetime(x, format="%Y %m %d %H %M"),
        index_col = ['Date'])

我得到的错误是:

Traceback (most recent call last):
  File "convertCSVtoNC.py", line 70, in <module>
    openFile(sys.argv[1:])
  File "convertCSVtoNC.py", line 30, in openFile
    df2 = createDataFrame(input_file, counter)
  File "convertCSVtoNC.py", line 43, in createDataFrame
    index_col = ['Date'])
...
TypeError: <lambda>() takes exactly 1 argument (5 given)

脚本对于 302 之前的输入运行良好,示例已格式化:

"Year","Month","Day","Hour","Minute","Direct","Diffuse","D_Global","D_IR","U_Global","U_IR","Zenith"
1976,1,1,0,3,-999.00,-999.00,-999.00,-999.00,-999.00,-999.00,95.751
1976,1,1,0,6,-999.00,-999.00,-999.00,-999.00,-999.00,-999.00,95.839
1976,1,1,0,9,-999.00,-999.00,-999.00,-999.00,-999.00,-999.00,95.930
1976,1,1,0,12,-999.00,-999.00,-999.00,-999.00,-999.00,-999.00,96.023

有什么想法吗?

【问题讨论】:

    标签: python csv pandas lambda


    【解决方案1】:

    对我来说很好用:

    df1 = pd.read_csv(file_name, parse_dates={'Date':[0,1,2,3,4]},
                      date_parser=lambda x: pd.to_datetime(x, format='%Y %m %d %H %M'),
                      index_col=['Date']))
    
    
    In [215]: df1
    Out[215]:
                         Direct  Diffuse  D_Global    D_IR  U_Global    U_IR  Zenith
    Date
    2001-03-01 00:01:00    0.28    84.53     83.53  224.93     76.67  228.31  80.031
    2001-03-01 00:02:00    0.15    84.24     83.25  224.76     76.54  228.62  80.059
    2001-03-01 00:03:00    0.16    84.63     83.43  225.62     76.76  229.06  80.087
    2001-03-01 00:04:00    0.20    85.20     83.99  226.56     77.15  228.96  80.115
    

    PS 我正在使用 Pandas 0.19.1

    【讨论】:

      【解决方案2】:

      原来在我的输入 csv 文件末尾有几个换行符。我想这是有道理的,因为我的 lambda 函数将整行作为输入。也许在未来的 lambda 相关问题中需要寻找一些东西。

      【讨论】:

        猜你喜欢
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        相关资源
        最近更新 更多