gpt4 book ai didi

python - 将英尺转换为 CM

转载 作者:行者123 更新时间:2023-12-04 03:33:56 24 4
gpt4 key购买 nike

    Name                  Team      Number  Position    Age    Height   Weight  College           Salary
1 Jae Crowder Boston Celtics 99.0 SF 25.0 6-6 235.0 Marquette 6796117.0
2 John Holland Boston Celtics 30.0 SG 2 7.0 6-5 205.0 Boston University NaN

你好,我有这张表,我想在新列中将高度从英尺转换为 CM,高度列 RN 既不是 float 也不是整数,所以我需要先提取它并对数字进行操作。

谢谢

最佳答案

使用 str 函数和点

可能更快的方法(矢量化)是使用 str 函数。

The operation you want to perform can be done by applying a dot-product between the 2 elements in your height column and the 2 conversion multipliers.

[feet, inches] @ [30.48, 2.54] = feet*30.48 + inches*2.54
  1. str.split 将字符串拆分为列表。
  2. 然后 apply(pd.Series) 将列表分成 2 个单独的列。
  3. 最后,astype(int) 将每个单元格转换为 int
  4. 最后,dot 使用转换乘数对每一行执行点积。
conversions = [30.48, 2.54]
df['new'] = df['Height'].str.split('-').apply(pd.Series).astype(int).dot(conversions)
0    198.12
1 167.64
2 35.56
dtype: float64

使用 lambda 函数和点

如果您对 lambda 函数更熟悉,这里是相同的代码 -

conversions = [30.48, 2.54]

df['new'] = df['Height'].apply(lambda x: pd.Series(map(int, x.split('-'))).dot(conversions))
0    198.12
1 167.64
2 35.56
dtype: float64

关于python - 将英尺转换为 CM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67314664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com