【问题标题】:python - Convert float into integer in a column pandaspython - 将浮点数转换为熊猫列中的整数
【发布时间】:2019-05-14 11:19:28
【问题描述】:

我有一个熊猫数据框:

df3 = pd.DataFrame({
'T': [11.0,22.0,11.23,20.03],
'v2': [11.0,13.0,55.1,33.0],
'v3' : [112.1,2.0,2.1,366.0],
'v4': [np.nan, "blue", 1.0, 2.0]
 })

       T    v2     v3    v4
0  11.00  11.0  112.1   NaN
1  22.00  13.0    2.0  blue
2  11.23  55.1    2.1   1.0
3  20.03  33.0  366.0   2.0

我必须有:

    T       v2     v3    v4
0  11     11.0  112.1   NaN
1  22     13.0    2.0  blue
2  11.23  55.1    2.1   1.0
3  20.03  33.0  366.0   2.0

所以我必须仅在“T”上将浮点数转换为整数。

【问题讨论】:

  • 你能在问题中添加更多内容吗?

标签: python pandas dataframe floating-point integer


【解决方案1】:

这是可能的,但有点hack,因为有必要转换为object

df3['T'] = np.array([int(x) if int(x) == x else x for x in df3['T']], dtype=object)
print (df3)
       T    v2     v3    v4
0     11  11.0  112.1   NaN
1     22  13.0    2.0  blue
2  11.23  55.1    2.1     1
3  20.03  33.0  366.0     2

print (df3['T'].tolist())
[11, 22, 11.23, 20.03]

如果可能的缺失值:

df3 = pd.DataFrame({
'T': [11.0,22.0,11.23,np.nan],
'v2': [11.0,13.0,55.1,33.0],
'v3' : [112.1,2.0,2.1,366.0],
'v4': [np.nan, "blue", 1.0, 2.0]
 })


df3['T'] = np.array([int(x) if x % 1 == 0 else x for x in df3['T']], dtype=object)
print (df3)
       T    v2     v3    v4
0     11  11.0  112.1   NaN
1     22  13.0    2.0  blue
2  11.23  55.1    2.1     1
3    NaN  33.0  366.0     2

print (df3['T'].tolist())
[11, 22, 11.23, nan]

【讨论】:

    【解决方案2】:

    使用与@jezrael 相同的想法,但使用is_integer

    import numpy as np
    import pandas as pd
    
    df3 = pd.DataFrame({
        'T': [11.0, 22.0, 11.23, 20.03],
        'v2': [11.0, 13.0, 55.1, 33.0],
        'v3': [112.1, 2.0, 2.1, 366.0],
        'v4': [np.nan, "blue", 1.0, 2.0]
    })
    
    df3['T'] = np.array([int(x) if float(x).is_integer() else x for x in df3['T']], dtype=object)
    
    print(df3)
    

    输出

    T    v2     v3    v4
    0     11  11.0  112.1   NaN
    1     22  13.0    2.0  blue
    2  11.23  55.1    2.1     1
    3  20.03  33.0  366.0     2
    

    或者使用numpy.wherenumpy.fmod

    mask = np.fmod(df3['T'].values, 1) == 0
    df3['T'] = np.where(mask, df3['T'].values.astype(np.int), df3['T']).astype(dtype=object)
    print(df3)
    

    【讨论】:

      【解决方案3】:

      或者为什么不:

      df3=df3.apply(lambda x: int(x) if int(x)==x and x==x and isinstance(x,float) else x)
      

      现在:

      print(df3)
      

      预计会输出:

          T       v2     v3    v4
      0  11     11.0  112.1   NaN
      1  22     13.0    2.0  blue
      2  11.23  55.1    2.1   1.0
      3  20.03  33.0  366.0   2.0
      

      【讨论】:

        猜你喜欢
        • 2013-10-02
        • 2019-12-07
        • 2020-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 2021-04-26
        相关资源
        最近更新 更多