要将数据框的某列设置为数值型,可以使用 astype() 函数将该列的数据类型转换为 floatint

以下是一个示例代码:

import pandas as pd

# 创建一个数据框
df = pd.DataFrame({'col1': ['1', '2', '3', '4'],
                   'col2': ['5', '6', '7', '8']})

# 将col1列转换为数值型
df['col1'] = df['col1'].astype(float)

# 输出转换后的数据框
print(df)

输出结果:

   col1 col2
0   1.0    5
1   2.0    6
2   3.0    7
3   4.0    8

在上面的代码中,我们使用 astype(float) 将 'col1' 列的数据类型转换为 float 型。同样的,如果要将其转换为整数型,可以使用 astype(int)

Pandas 数据框列数据类型转换:数值型

原文地址: https://www.cveoy.top/t/topic/qzCG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录