Python pandas: output dataframe to csv with integers

后端 未结 6 683
囚心锁ツ
囚心锁ツ 2020-12-08 02:15

I have a pandas.DataFrame that I wish to export to a CSV file. However, pandas seems to write some of the values as float instead of int

6条回答
  •  一生所求
    2020-12-08 02:57

    If you want to preserve NaN info in the csv which you have exported, then do the below. P.S : I'm concentrating on column 'C' in this case.

    df[c] = df[c].fillna('')       #filling Nan with empty string
    df[c] = df[c].astype(str)      #convert the column to string 
    >>> df
        a   b    c     d
    x  10  10         10
    y   1   5    2.0   3
    z   1   2    3.0   4
    
    df[c] = df[c].str.split('.')   #split the float value into list based on '.'
    >>> df
            a   b    c          d
        x  10  10   ['']       10
        y   1   5   ['2','0']   3
        z   1   2   ['3','0']   4
    
    df[c] = df[c].str[0]            #select 1st element from the list
    >>> df
        a   b    c   d
    x  10  10       10
    y   1   5    2   3
    z   1   2    3   4
    

    Now, if you export the dataframe to csv, Column 'c' will not have float values and the NaN info is preserved.

提交回复
热议问题