在Pandas中将浮动转换为int?

问题描述 投票:162回答:9

我一直在处理从CSV导入的数据。 Pandas将一些列更改为float,所以现在这些列中的数字显示为浮点数!但是,我需要将它们显示为整数,或者不使用逗号。有没有办法将它们转换为整数或不显示逗号?

python pandas floating-point integer dataset
9个回答
171
投票

要修改浮点输出,请执行以下操作:

df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df

Out[33]:

          a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000

pd.options.display.float_format = '{:,.0f}'.format
df

Out[35]:

   a
0  0
1  1
2  2
3  3
4  4

138
投票

使用.astype(<type>)函数来操作列dtypes。

>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

编辑:

要处理缺失的值:

>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0
>>>

25
投票

使用列名列表,使用.applymap()更改多列的类型,或使用.apply()更改单个列的类型。

    df = pd.DataFrame(10*np.random.rand(3, 4), columns=list("ABCD"))

              A         B         C         D
    0  8.362940  0.354027  1.916283  6.226750
    1  1.988232  9.003545  9.277504  8.522808
    2  1.141432  4.935593  2.700118  7.739108

    cols = ['A', 'B']
    df[cols] = df[cols].applymap(np.int64)

       A  B         C         D
    0  8  0  1.916283  6.226750
    1  1  9  9.277504  8.522808
    2  1  4  2.700118  7.739108

    df['C'] = df['C'].apply(np.int64)
       A  B  C         D
    0  8  0  1  6.226750
    1  1  9  9  8.522808
    2  1  4  2  7.739108

7
投票

如果您想将Pandas DataFrame df的更多列从float转换为整数,这是一个快速的解决方案,同时考虑到您可以拥有NaN值的情况。

cols = ['col_1', 'col_2', 'col_3', 'col_4']
for col in cols:
   df[col] = df[col].apply(lambda x: int(x) if x == x else "")

我尝试过:

 else x)
 else None)

但结果仍然有浮点数,所以我使用了else ""


5
投票
import pandas as pd;
right = pd.DataFrame({'C': [1.002, 2.003],
               'D': [1.009, 4.55],
                "key":['K0', 'K1']})


           C    D   key
0   1.002   1.009   K0
1   2.003   4.550   K1

right['C'] = right.C.astype(int)

       C    D   key
0   1   1.009   K0
1   2   4.550   K1

4
投票

扩展@Ryan G提到了.astype(<type>)函数的使用,可以使用errors=ignore参数仅转换那些不产生错误的列,这显着简化了语法。显然,在忽略错误时应该谨慎,但是对于这个任务来说它非常方便。

df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
df *= 10
df

    A       B       C       D
0   2.16861 8.34139 1.83434 6.91706
1   5.85938 9.71712 5.53371 4.26542
2   0.50112 4.06725 1.99795 4.75698

df['E'] = list("XYZ")
df.astype(int, errors='ignore')

    A   B   C   D   E
0   2   8   1   6   X
1   5   9   5   4   Y
2   0   4   1   4   Z

来自astype文档:

错误:{'加注','忽略'},默认'加注'

控制提供dtype的无效数据的异常。

  • raise:允许引发异常
  • 忽略:抑制异常。出错时返回原始对象

版本0.20.0中的新功能。


2
投票

**

将所有浮点列转换为int

**

df = pd.DataFrame(np.random.rand(5,4) * 10, columns=list("PQRS"))

df
    P           Q           R           S
0   4.395994    0.844292    8.543430    1.933934
1   0.311974    9.519054    6.171577    3.859993
2   2.056797    0.836150    5.270513    3.224497
3   3.919300    8.562298    6.852941    1.415992
4   9.958550    9.013425    8.703142    3.588733


float_col = df.select_dtypes(include = ['float64']) # This will select float columns only
# list(float_col.columns.values)
for col in float_col.columns.values:
    df[col] = df[col].astype('int64')

df

    P   Q   R   S
0   4   0   8   1
1   0   9   6   3
2   2   0   5   3
3   3   8   6   1
4   9   9   8   3

0
投票

这是一个简单的函数,它将浮点数转换为最小的整数类型,不会丢失任何信息。举些例子,

  • 100.0可以从float转换为整数,但99.9不能(不会丢失舍入或截断的信息)
  • 另外,1.0可以向下传播到int8而不会丢失信息,但100_000.0的最小整数类型是int32

代码示例:

import numpy as np
import pandas as pd

def float_to_int( s ):
    if ( s.astype(np.int64) == s ).all():
        return pd.to_numeric( s, downcast='integer' )
    else:
        return s

# small integers are downcast into 8-bit integers
float_to_int( np.array([1.0,2.0]) )
Out[1]:array([1, 2], dtype=int8)

# larger integers are downcast into larger integer types
float_to_int( np.array([100_000.,200_000.]) )
Out[2]: array([100000, 200000], dtype=int32)

# if there are values to the right of the decimal
# point, no conversion is made
float_to_int( np.array([1.1,2.2]) )
Out[3]: array([ 1.1,  2.2])

-3
投票
df_18['cyl'].value_counts()

4.0 365

6.0 246

8.0 153

名称:cyl,dtype:int64在[38]中:

int df_18 ['cyl'] = df_18 ['cyl']。astype(int)

4 365

6 246

8 153

名称:cyl,dtype:int64

© www.soinside.com 2019 - 2024. All rights reserved.