Read data from CSV file and transform from string to correct data-type, including a list-of-integer column

前端 未结 7 1508
难免孤独
难免孤独 2020-11-28 09:44

When I read data back in from a CSV file, every cell is interpreted as a string.

  • How can I automatically convert the data I read in into the correct type?
相关标签:
7条回答
  • 2020-11-28 10:32

    I love @martineau's answer. It's very clean.

    One thing I needed was to convert only a couple of values and leave all the other fields as strings, like having strings as default and just updating the type for specific keys.

    To do that, just replace this line:

    row = CSV_Record._transform(row)
    

    by this one:

    row.update(CSV_Record._transform(row))
    

    The 'update' function updates the variable row directly, merging the raw data from the csv extract with the values converted to the correct type by the '_transform' method.

    Note there is no 'row = ' in the updated version.

    Hope this will help in case anyone has a similar requirement.

    (PS: I'm quite new to posting on stackoverflow, so please let me know if the above is not clear)

    0 讨论(0)
提交回复
热议问题