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

时间:2018-02-22 15:32:26

标签: python pandas casting

我正在使用充满浮点数的pandas DataFrames,但每三行使用一个整数(整行由整数组成)。当我创建一个print df时,显示的所有值都显示为浮点数(整数值有一个“.000000```added),例如:

                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

当我使用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

当我使用df.to_csv("mydf.csv", sep=",", encoding="utf-8")时,整数被写为浮点数;如何强制写入这些行的整数?将数据拆分为两个DataFrame会更好吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需致电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