Reading back tuples from a csv file with pandas

后端 未结 1 565
我在风中等你
我在风中等你 2020-12-16 20:20

Using pandas, I have exported to a csv file a dataframe whose cells contain tuples of strings. The resulting file has the following structure:

index,colA
1,\         


        
相关标签:
1条回答
  • 2020-12-16 21:16

    Storing tuples in a column isn't usually a good idea; a lot of the advantages of using Series and DataFrames are lost. That said, you could use converters to post-process the string:

    >>> df = pd.read_csv("sillytup.csv", converters={"colA": ast.literal_eval})
    >>> df
       index    colA
    0      1  (a, b)
    1      2  (c, d)
    
    [2 rows x 2 columns]
    >>> df.colA.iloc[0]
    ('a', 'b')
    >>> type(df.colA.iloc[0])
    <type 'tuple'>
    

    But I'd probably change things at source to avoid storing tuples in the first place.

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