python - 将英尺转换为 CM

标签 python pandas dataframe

    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/

相关文章:

python - 如何将频谱图数据转换为张量(或多维 numpy 数组)?

pandas - 将滚动函数应用于多列的 groupby

python - pickle 数据框

python - 使用 Pandas 将数据框中的多列转换为两个新列

python - 计算最频繁的值并对其进行操作

python - InstaPy: "Error, unable to determine correct filename for 64bit linux"

python - 在Python中打开xlxs工作簿,自动命名文件

python - 如何在 for 循环中正确地将列表附加到 DataFrame

python - Django:request.GET 和 KeyError

python - 按元素检查字符串是否存在