📌  相关文章
📜  在 Pandas DataFrame 中将浮点数转换为整数

📅  最后修改于: 2022-05-13 01:54:24.293000             🧑  作者: Mango

在 Pandas DataFrame 中将浮点数转换为整数

让我们看看如何在 Pandas DataFrame 中将浮点数转换为整数。我们将使用astype()方法来执行此操作。也可以使用apply()方法来完成。

方法一:使用DataFrame.astype()方法

首先,我们将创建一个 DataFrame:

# importing the library
import pandas as pd
  
# creating a DataFrame
list = [['Anton Yelchin', 36, 75.2, 54280.20], 
        ['Yul Brynner', 38, 74.32, 34280.30], 
        ['Lev Gorn', 31, 70.56, 84280.50],
        ['Alexander Godunov', 34, 80.30, 44280.80], 
        ['Oleg Taktarov', 40, 100.03, 45280.30],
        ['Dmitriy Pevtsov', 33, 72.99, 70280.25], 
        ['Alexander Petrov', 42, 85.84, 25280.75]]
df = pd.DataFrame(list, columns =['Name', 'Age', 'Weight', 'Salary'])
display(df)

输出 :

示例 1:使用DataFrame.astype()列从 float 转换为 int

# displaying the datatypes
display(df.dtypes)
  
# converting 'Weight' from float to int
df['Weight'] = df['Weight'].astype(int)
  
# displaying the datatypes
display(df.dtypes)

输出 :

示例 2:使用DataFrame.astype()列从 float 转换为 int

# displaying the datatypes
display(df.dtypes)
  
# converting 'Weight' and 'Salary' from float to int
df = df.astype({"Weight":'int', "Salary":'int'}) 
  
# displaying the datatypes
display(df.dtypes)

输出 :

方法二:使用DataFrame.apply()方法

首先,我们将创建一个 DataFrame。

# importing the module
import pandas as pd
  
# creating a DataFrame
list = [[15, 2.5, 100.22], [20, 4.5, 50.21], 
        [25, 5.2, 80.55], [45, 5.8, 48.86], 
        [40, 6.3, 70.99], [41, 6.4, 90.25], 
        [51, 2.3, 111.90]]
df = pd.DataFrame(list, columns = ['Field_1', 'Field_2', 'Field_3'],
                  index = ['a', 'b', 'c', 'd', 'e', 'f', 'g'])
display(df)

输出 :

示例 1:使用DataFrame.apply(np.int64)单列从 float 转换为 int

# importing the module
import numpy as np
  
# displaying the datatypes
display(df.dtypes)
  
# converting 'Field_2' from float to int
df['Field_2'] = df['Field_2'].apply(np.int64)
  
# displaying the datatypes
display(df.dtypes)

输出 :

示例 2:使用DataFrame.apply(np.int64)列从 float 转换为 int

# displaying the datatypes
display(df.dtypes)
  
# converting 'Field_2' and 'Field_3' from float to int
df['Field_2'] = df['Field_2'].apply(np.int64)
df['Field_3'] = df['Field_3'].apply(np.int64)
  
# displaying the datatypes
display(df.dtypes)

输出 :