【问题标题】:Why df have '.0' when I to txt?为什么当我要 txt 时 df 有 '.0'?
【发布时间】:2020-04-21 06:00:10
【问题描述】:
t=pd.DataFrame(tree_pre)

t.fillna('',inplace=True)

print(t)

    0   1   2   3   4   5   6   7 8
0          55                      
1      30                  70      
2  25                  65      85  
3              60                  
4                  64  

但是当我要 txt 时

t.to_csv('2020.txt',sep='\t',index=False,header=False)

txt 有 '.0'

    55.0                        
30.0                    70.0        

25.0 65.0 85.0
60.0
64.0

为什么我在 txt 时 df 有 '.0'?

【问题讨论】:

标签: python pandas


【解决方案1】:

您需要添加格式说明符,这应该可以:

t.to_csv('2020.txt',sep='\t',index=False,header=False,float_format='%.0f')

【讨论】:

  • 不知道,我还以为是他们打开的程序导致的。
【解决方案2】:

为什么我在 txt 时 df 有 '.0'?

numpy.nan 是 float 的一个实例,因此任何带有 nan 的列都是浮点类型。

>>> df = pd.DataFrame([[1,2,np.nan,np.nan,4],[4,np.nan,5,np.nan,6]])
>>> df
   0    1    2   3  4
0  1  2.0  NaN NaN  4
1  4  NaN  5.0 NaN  6

>>> df.dtypes
0      int64
1    float64
2    float64
3    float64
4      int64
dtype: object

>>> isinstance(df.iloc[0,2],float)
True

>>> df.fillna('',inplace=True)
>>> df.iloc[0,1]
2.0
>>> 

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 2021-01-20
    • 2019-09-03
    • 2017-01-04
    • 2014-08-04
    • 1970-01-01
    • 2021-11-07
    • 2021-04-03
    相关资源
    最近更新 更多