简体   繁体   English

在csv文件中编写一个混合整数和浮点数的pandas DataFrame

[英]Write a pandas DataFrame mixing integers and floats in a csv file

I'm working with pandas DataFrames full of float numbers, but with integers in one every three lines (the whole line is made of integers).我正在使用充满浮点数的 Pandas DataFrames,但每三行一个整数(整行由整数组成)。 When I make a print df , all the values displayed are shown as floats (the integers values have a ``.000000```added) for example :当我print df ,显示的所有值都显示为浮点数(整数值添加了“.000000”),例如:

                aromatics      charged        polar      unpolar
Ac_obs_counts  712.000000  1486.000000  2688.000000  2792.000000
Ac_obs_freqs     0.092732     0.193540     0.350091     0.363636
Ac_pvalues       0.524752     0.099010     0.356436     0.495050
Am_obs_counts   10.000000    59.000000    62.000000    50.000000
Am_obs_freqs     0.055249     0.325967     0.342541     0.276243
Am_pvalues       0.495050     0.980198     0.356436     0.009901
Ap_obs_counts   18.000000    34.000000    83.000000    78.000000
Ap_obs_freqs     0.084507     0.159624     0.389671     0.366197
Ap_pvalues       0.524752     0.039604     0.980198     0.663366

When I use df.iloc[range(0, len(df.index), 3)] , I see integers displayed :当我使用df.iloc[range(0, len(df.index), 3)] ,我看到整数显示:

               aromatics  charged  polar  unpolar
Ac_obs_counts        712     1486   2688     2792
Am_obs_counts         10       59     62       50
Ap_obs_counts         18       34     83       78
Pa_obs_counts         47       81    125      144
Pf_obs_counts         31       58     99      109
Pg_obs_counts         27      106    102      108
Ph_obs_counts          7       49     42       36
Pp_obs_counts         15       83     45       65
Ps_obs_counts         57      125    170      216
Pu_obs_counts         14       62    102       84

When I use df.to_csv("mydf.csv", sep=",", encoding="utf-8") , the integers are written as floats ;当我使用df.to_csv("mydf.csv", sep=",", encoding="utf-8") ,整数被写为浮点数; how can I force the writing as integers for these lines ?如何强制将这些行写入为整数? Would it be better to split the data in two DataFrames ?将数据拆分为两个 DataFrame 会更好吗?

Thanks in advance.提前致谢。

Simply call object简单地调用object

df.astype('object')
Out[1517]: 
              aromatics   charged     polar   unpolar
Ac_obs_counts       712      1486      2688      2792
Ac_obs_freqs   0.092732   0.19354  0.350091  0.363636
Ac_pvalues     0.524752   0.09901  0.356436   0.49505
Am_obs_counts        10        59        62        50
Am_obs_freqs   0.055249  0.325967  0.342541  0.276243
Am_pvalues      0.49505  0.980198  0.356436  0.009901
Ap_obs_counts        18        34        83        78
Ap_obs_freqs   0.084507  0.159624  0.389671  0.366197
Ap_pvalues     0.524752  0.039604  0.980198  0.663366

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM