如何在 pandas 中将字符串转换为浮点数


您可以使用以下方法将字符串转换为 pandas 中的浮点数:

方法一:将单列转换为浮点数

 #convert "assists" column from string to float
df[' assists '] = df[' assists ']. astype (float)

方法 2:将多列转换为浮点型

 #convert both "assists" and "rebounds" from strings to floats
df[[' assists ', ' rebounds ']] = df[[' assists ', ' rebounds ']]. astype (float)

方法 3:将所有列转换为浮点型

 #convert all columns to float
df = df. astype (float)

以下示例展示了如何在实践中使用以下 pandas DataFrame 的每种方法:

 import numpy as np
import pandas as pd

#createDataFrame
df = pd. DataFrame ({' points ': [np.nan, 12, 15, 14, 19],
                   ' assists ': ['5', np.nan, '7', '9', '12'],
                   ' rebounds ': ['11', '8', '10', '6', '6']})  

#view DataFrame
df

 	points assists rebounds
0 NaN 5.0 11
1 12.0 NaN 8
2 15.0 7.0 10
3 14.0 9.0 6
4 19.0 12.0 6

#view column data types
df. dtypes

float64 points
assists object
rebound object
dtype:object

示例 1:将单列转换为浮点型

以下语法显示如何将辅助列从字符串转换为浮点数:

 #convert "assists" from string to float
df[' assists '] = df[' assists ']. astype (float)

#view column data types
df. dtypes

float64 points
assist float64
rebound object
dtype:object

示例 2:将多列转换为 float

以下语法显示了如何将辅助列反弹列从字符串转换为浮点数:

 #convert both "assists" and "rebounds" from strings to floats
df[[' assists ', ' rebounds ']] = df[[' assists ', ' rebounds ']]. astype (float)

#view column data types
df. dtypes

float64 points
assist float64
rebounds float64
dtype:object

示例 3:将所有列转换为浮点型

以下语法显示了如何将 DataFrame 中的所有列转换为浮点数:

 #convert all columns to float
df = df. astype (float)

#view column data types
df. dtypes

float64 points
assist float64
rebounds float64
dtype:object

奖励:将字符串转换为浮点数并填充 NaN 值

以下语法显示了如何将辅助列从字符串转换为浮点数,并同时用零填充 NaN 值:

 #convert "assists" from string to float and fill in NaN values with zeros
df[' assists '] = df[' assists ']. astype (float). fillna (0)

#view DataFrame
df

        points assists rebounds
0 NaN 5.0 11
1 12.0 0.0 8
2 15.0 7.0 10
3 14.0 9.0 6
4 19.0 12.0 6

其他资源

以下教程解释了如何在 pandas 中执行其他常见任务:

Pandas:如何将对象转换为整数
Pandas:如何将浮点数转换为整数
Pandas:如何将特定列转换为 NumPy 数组

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注