【问题标题】:Python dataframe zero value formatPython数据帧零值格式
【发布时间】:2021-04-07 17:13:05
【问题描述】:

我有一个数据框:

Col1   Col2         Col3         Col4
AAA      30   0.00000005   0.00000000
BBB       0   0.00000000   0.00000000
CCC      55   3.00554440   0.00000000

df.dtypes
Col1   object
Col2   int64
Col3   float64
Col4   float64

我想重新格式化float 类型列。
如果浮点列中的值为“0”,则将格式设置为整数“0”。否则,“.6f”。

Col1   Col2       Col3       Col4
AAA      30   0.000000          0
BBB       0          0          0
CCC      55   3.005544   0.000000

我怎样才能像这样重新格式化?

【问题讨论】:

    标签: python pandas data-manipulation


    【解决方案1】:

    类似这样的:

    In [1692]: cols = df.select_dtypes('float').columns
    In [1694]: df[cols] = np.where(df.select_dtypes('float').eq(0), 0, df.select_dtypes('float').applymap(lambda x: round(x, 6)))
    
    In [1695]: df
    Out[1695]: 
      Col1  Col2      Col3  Col4
    0  AAA    30  0.000000   0.0
    1  BBB     0  0.000000   0.0
    2  CCC    55  3.005544   0.0
    

    【讨论】:

      【解决方案2】:

      根据我收集的信息,您可以制作自己的显示功能并与df.style应用相同

      float_cols= df.columns[df.dtypes.values==np.dtype('float64')]
      def myformat(d):
          d1 = pd.DataFrame(np.where(d==0,'.0f','.6f'),d.index,d.columns)
          return d1
      df.style.apply(myformat,axis=None,subset=float_cols)
      

      【讨论】:

      • 仍然得到 0.000000
      • @PeterChen 代表哪一栏?您可以为您发布的 df 发布df.to_dict() 作为示例尝试吗?浮动可能很棘手
      猜你喜欢
      • 2017-08-20
      • 2019-04-05
      • 2023-03-04
      • 1970-01-01
      • 2015-12-19
      • 2022-07-28
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多