python - 替换 Pandas 中的列值

标签 python pandas type-conversion data-analysis

我在数据集中有一列“高度”,如下所示。

      Height
0       6-2
1       6-6
2       6-5
3       6-5
4      6-10
5       6-9
6       6-8
7       7-0

它的类型是dtype: object 现在我想将它转换为 float ,即6.2、6.6 我尝试使用替换方法,但它不起作用。你能建议我该怎么做吗?我是 Pandas 新手。

最佳答案

使用Series.str.replace用于替换子字符串并转换为 float :

df['Height'] = df['Height'].str.replace('-','.').astype(float)

或者使用Series.replace使用 regex=True 替换子字符串:

df['Height'] = df['Height'].replace('-','.', regex=True).astype(float)

关于python - 替换 Pandas 中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55729179/

相关文章:

python - 在 Web 应用程序中处理类源数据文件的最佳方式是什么?

python - 使用 Python 在 Windows 中注销或切换用户

r - 将 data.frame 列转换为向量?

python - 在 seaborn stripplot 中为点添加标签

python - 在 Python Pandas 中使用 groupby 从 bool (真/假)列返回百分比结果

objective-c - 快速获取 float

c - 为什么 MISRA-C 在某些情况下不允许隐式扩大类型?

python - 列表理解和功能函数是否比 "for loops"更快?

python - 寻找离散函数的全局最小值

python - 操作列时如何使用 pandas 数据帧处理 "divide by zero"?