Exporting superscript notation in pandas dataframe to csv or excel

孤者浪人 提交于 2021-02-18 19:48:16

问题


I would like to write the foll. to a csv file:

  df.loc[0] = ['Total (2000)',
                       numpy.nan,
                       numpy.nan,
                       numpy.nan,
                       2.0,
                       1.6,
                       '10^6 km^2']

Is there a way to do that while writing '10^6 km^2' in a format such that the 6 is a superscript to 10 and 2 is a superscript to km. If not possible in csv, can I export to excel?


回答1:


One possible way is to change the actual contents of the dataframe before writing it to a csv (but you can automate this somewhat).

As a proof of concept, using '\u2076' as the unicode representation of superscript 6:

In [21]: df
Out[21]: 
              a   b   c   d  e    f          g
0  Total (2000) NaN NaN NaN  2  1.6  10^6 km^2

In [30]: df['g'] = (df['g'].str.replace("10\^6", u"10\u2076")
    ...:                   .str.replace("km\^2", u"km\u00b2"))

In [31]: df
Out[31]: 
              a   b   c   d  e    f        g
0  Total (2000) NaN NaN NaN  2  1.6  10⁶ km²

In [32]: print df.to_csv(encoding='UTF-8', index=False)
a,b,c,d,e,f,g
Total (2000),,,,2.0,1.6,10⁶ km²


来源:https://stackoverflow.com/questions/35226463/exporting-superscript-notation-in-pandas-dataframe-to-csv-or-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!