在Pandas中将float64列转换为int64

时间:2017-05-13 18:01:52

标签: python pandas dataframe

我尝试使用以下内容将数据类型float64中的列转换为int64

df['column name'].astype(int64)

但收到了错误:

  

NameError:name' int64'未定义

该列有多少人,但格式为7500000.0,我知道如何将此float64更改为int64

4 个答案:

答案 0 :(得分:42)

pandas 0.24 + 的解决方案,用于转换带缺失值的数字:

df = pd.DataFrame({'column name':[7500000.0,7500000.0, np.nan]})
print (df['column name'])
0    7500000.0
1    7500000.0
2          NaN
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)
  

ValueError:无法将非有限值(NA或inf)转换为整数

#http://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html
df['column name'] = df['column name'].astype('Int64')
print (df['column name'])
0    7500000
1    7500000
2        NaN
Name: column name, dtype: Int64

我认为你需要施展到numpy.int64

df['column name'].astype(np.int64)

样品:

df = pd.DataFrame({'column name':[7500000.0,7500000.0]})
print (df['column name'])
0    7500000.0
1    7500000.0
Name: column name, dtype: float64

df['column name'] = df['column name'].astype(np.int64)
#same as
#df['column name'] = df['column name'].astype(pd.np.int64)
print (df['column name'])
0    7500000
1    7500000
Name: column name, dtype: int64

如果列中的某些NaN需要将int替换为某些0(例如typefillna,因为NaN floatdf = pd.DataFrame({'column name':[7500000.0,np.nan]}) df['column name'] = df['column name'].fillna(0).astype(np.int64) print (df['column name']) 0 7500000 1 0 Name: column name, dtype: int64

NaN

同时检查documentation - missing data casting rules

编辑:

使用df = pd.DataFrame({'column name':[7500000.0,np.nan]}) df['column name'] = df['column name'].values.astype(np.int64) print (df['column name']) 0 7500000 1 -9223372036854775808 Name: column name, dtype: int64 转换值是错误的:

email

答案 1 :(得分:4)

您可能需要传入字符串'int64'

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]})  # some test dataframe

>>> df['a'].astype('int64')
0    1
1    2
Name: a, dtype: int64

有一些替代方法可以指定64位整数:

>>> df['a'].astype('i8')      # integer with 8 bytes (64 bit)
0    1
1    2
Name: a, dtype: int64

>>> import numpy as np
>>> df['a'].astype(np.int64)  # native numpy 64 bit integer
0    1
1    2
Name: a, dtype: int64

或直接在列上使用np.int64(但会返回numpy.array):

>>> np.int64(df['a'])
array([1, 2], dtype=int64)

答案 2 :(得分:1)

这在熊猫0.23.4中似乎有点小问题?

如果存在np.nan值,则将按预期抛出错误:

df['col'] = df['col'].astype(np.int64)

但是不会像我期望的那样使用“ ignore”来将任何值从float更改为int:

df['col'] = df['col'].astype(np.int64,errors='ignore') 

如果我第一次转换np.nan,它会起作用:

df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)

现在我无法弄清楚如何弄清如何将空值代替零,因为这会将所有内容重新转换为浮点数:

df['col']  = df['col'].replace(0,np.nan)

答案 3 :(得分:0)

考虑使用

df['column name'].astype('Int64')

nan将更改为NaN