用 Python 编写一个程序来转换数据帧中特定列的数据类型
假设您有一个数据框,将float转换为int的结果为,
Before conversion Name object Age int64 Maths int64 Science int64 English int64 Result float64 dtype: object After conversion Name object Age int64 Maths int64 Science int64 English int64 Result int64 dtype: object
为了解决这个问题,我们将按照下面给出的步骤-
解决方案
定义数据框
将浮点数据类型列'Result'转换为'int',如下所示-
df.Result.astype(int)
例子
让我们看看下面的实现以获得更好的理解-
import pandas as pd
data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
'Age' : [13,12,12,13,12],
'Maths': [98, 59, 66, 95, 70],
'Science': [75, 96, 55, 49, 78],
'English': [79, 45, 70, 60, 80],
'Result': [8.1,6.2,6.3,7.2,8.3]}
df = pd.DataFrame(data)
print("Before conversion\n", df.dtypes)
df.Result = df.Result.astype(int)
print("After conversion\n",df.dtypes)输出
Name object Age int64 Maths int64 Science int64 English int64 Result float64 dtype: object Name object Age int64 Maths int64 Science int64 English int64 Result int64 dtype: object
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下