Python - 将Pandas中的浮点数转换为整数

3

I have a pandas dataframe as:

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”上将浮点数转换为整数。


你能否在问题中添加更多内容? - Joseph
3个回答

5

这是有可能的,但需要一点技巧,因为需要转换成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]

0

使用与@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)

0

或者为什么不这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接