How do I change data-type of pandas data frame to string with a defined format?

后端 未结 3 2003
醉酒成梦
醉酒成梦 2020-12-24 02:14

I\'m starting to tear my hair out with this - so I hope someone can help. I have a pandas DataFrame that was created from an Excel spreadsheet using openpyxl. The resulting

相关标签:
3条回答
  • 2020-12-24 02:53

    If you could reload this, you might be able to use dtypes argument.

    pd.read_csv(..., dtype={'COL_NAME':'str'})
    
    0 讨论(0)
  • 2020-12-24 02:55

    I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

    s = pd.Series([1001.,1002.,None])
    a = s.loc[s.isnull()].fillna('')
    b = s.loc[s.notnull()].astype(int).astype(str)
    result = pd.concat([a,b])
    
    0 讨论(0)
  • 2020-12-24 03:03

    I'm unable to reproduce your problem but have you tried converting it to an integer first?

    image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
    

    Then, regarding your more general question you could use map (as in this answer). In your case:

    image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
    
    0 讨论(0)
提交回复
热议问题