首先创建高度值的数据框
让我们首先设置一个 Pandas 数据框来匹配问题。然后使用 apply 将英尺和英寸显示的值转换为数值。注意:提问者询问这些值是否可以转换为整数,但是 'HeightNoShoes' 列中的第一个值是 7' 5.5" 由于此字符串值以半英寸表示,因此它将首先转换为浮点值。然后您可以在将值键入为整数之前使用 round 函数对其进行舍入。
# libraries
import pandas as pd
# height data
no_shoes = ['''7' 5.5"''',
'''6' 11"''',
'''6' 7.75"''',
'''6' 5.5" ''',
'''5' 11"''']
shoes = [np.nan,
'''7' 0.25"''',
'''6' 9"''',
'''6' 6.75"''',
'''6' 0"''']
# put height data into a Pandas dataframe
height_data = pd.DataFrame({'HeightNoShoes':no_shoes, 'HeightShoes':shoes})
height_data.head()
接下来使用函数将英尺转换为浮点值
这是一个将英尺和英寸转换为浮点值的函数。
def feet_to_float(cell_string):
try:
split_strings = cell_string.replace('"','').replace("'",'').split()
float_value = float(split_strings[0])+float(split_strings[1])
except:
float_value = np.nan
return float_value
接下来,将函数应用于数据框中的每一列。
# obtain a copy of the height data
df = height_data.copy()
for col in df.columns:
print(col)
df[col] = df[col].apply(feet_to_float)
df.head()
这是一个将浮点值转换为 Pandas 列中具有 NaN 值的整数值的函数
如果您想将数据框转换为在一列中具有 NaN 值的整数值,您可以使用以下函数和代码。请注意,该函数先将值四舍五入,然后再将它们类型转换为整数。 在四舍五入之前将浮点值类型转换为整数只会截断这些值。
def float_to_int(cell_value):
try:
return int(round(cell_value,0))
except:
return cell_value
for col in df.columns:
df[col] = df[col].apply(feet_to_float)
注意:Pandas 将同时包含 NaN 值和整数的列显示为浮点值。
这是将数据框中的单个列转换为数值的代码。
df = height_data.copy()
df['HeightNoShoes'] = df['HeightNoShoes'].apply(feet_to_float)
df.head()
这是将单列浮点值转换为整数的方法。请注意,首先对值进行四舍五入很重要。 在四舍五入之前将值类型转换为整数会错误地截断这些值。
df['HeightNoShoes'] = round(df['HeightNoShoes'],0).astype(int)
df.head()
在标记为 'HeightShoes' 的第二个 Pandas 列中有 NaN 值。上面找到的 feet_to_float 和 float_to_int 函数都应该能够处理这些。
df = height_data.copy()
df['HeightShoes'] = df['HeightShoes'].apply(feet_to_float)
df['HeightShoes'] = df['HeightShoes'].apply(float_to_int)
df.head()