简体   繁体   English

python - 在列pandas中将float转换为整数

[英]python - Convert float into integer in a column pandas

I have a pandas dataframe as: 我有一个pandas数据帧:

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

and I must have: 我必须:

    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

So I have to transform float to integer only on 'T.' 所以我必须只在'T'上将float转换为整数

It is possible, but a bit hack, because is necessary converting to object : 有可能,但有点黑客,因为必须转换为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]

If possible missing values: 如果可能缺少值:

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]

Using the same idea of @jezrael but with is_integer : 使用与@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)

Output 产量

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

Or using numpy.where with numpy.fmod : 或者使用numpy.fmodnumpy.where

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)

Or why not: 或者为什么不:

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

And now: 现在:

print(df3)

Is gonna be expected output: 会有预期的输出:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM