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


当前回答

使用'Int64'支持NaN

Astype (int)和Astype ('int64')不能处理缺失值(numpy int) astype('Int64')(注意大写I)可以处理缺失值(pandas int)

df['A'] = df['A'].astype('Int64') # capital I

这假设您希望将缺失的值保留为NaN。如果你打算归因他们,你可以按照Ryan的建议先填写na。


'Int64'(大写I)的例子

If the floats are already rounded, just use astype: df = pd.DataFrame({'A': [99.0, np.nan, 42.0]}) df['A'] = df['A'].astype('Int64') # A # 0 99 # 1 <NA> # 2 42 If the floats are not rounded yet, round before astype: df = pd.DataFrame({'A': [3.14159, np.nan, 1.61803]}) df['A'] = df['A'].round().astype('Int64') # A # 0 3 # 1 <NA> # 2 2 To read int+NaN data from a file, use dtype='Int64' to avoid the need for converting at all: csv = io.StringIO(''' id,rating foo,5 bar, baz,2 ''') df = pd.read_csv(csv, dtype={'rating': 'Int64'}) # id rating # 0 foo 5 # 1 bar <NA> # 2 baz 2


笔记

'Int64'是Int64Dtype的别名: df['A'] = df['A'].astype(pd.Int64Dtype()) #与astype('Int64')相同 大小/签名别名可用: 下界 上界 “Int8” -128年 127 “Int16” -32768年 32767年 “Int32” -2147483648年 2147483647年 “Int64” -9223372036854775808年 9223372036854775807年 “UInt8” 0 255 “UInt16” 0 65535年 “UInt32” 0 4294967295年 “UInt64” 0 18446744073709551615年

其他回答

>>> import pandas as pd
>>> right = pd.DataFrame({'C': [1.002, 2.003], 'D': [1.009, 4.55], 'key': ['K0', 'K1']})
>>> print(right)
           C      D key
    0  1.002  1.009  K0
    1  2.003  4.550  K1
>>> right['C'] = right.C.astype(int)
>>> print(right)
       C      D key
    0  1  1.009  K0
    1  2  4.550  K1

使用pandas. datafframe .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

需要转换为int的列也可以在字典中提到,如下所示

df = df.astype({'col1': 'int', 'col2': 'int', 'col3': 'int'})

要修改浮点数输出,可以这样做:

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

这是一个快速的解决方案,如果你想转换更多的列的熊猫。DataFrame从浮点数到整数也考虑到你可以有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 ""。