如何将CSV文件列中的高度更改为英寸

2024-06-29 00:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python、熊猫等都非常陌生

我正在尝试将“高度”列转换为英寸。你知道吗

首先,我是卡住了,并有这个代码到目前为止,它似乎是一种工作,但它不再。列中有一个NaN值,所以我试图跳过该行。你知道吗

第二,在代码运行之后,如何更改原始CSV而不是Pandas数据帧。你知道吗

Here是数据集的链接,这是我迄今为止编写的代码:

import pandas as pd

filename = r"C:\Users\jackw\Downloads\player_data.csv"
bball_data = pd.read_csv(filename)

df = pd.DataFrame(bball_data)


def height_convert(player_height):
    player_height = str(player_height)

    feet = float(player_height[0])
    inches = float(player_height[-1])

    new_height = float((feet * 12) + inches)

    return new_height


for value in df['height']:

    if value[0] != ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
        continue
    value = height_convert(value)



Tags: csv数据代码convertdfdatavaluefloat
1条回答
网友
1楼 · 发布于 2024-06-29 00:38:06

您的代码将无法工作,因为您正在使用player_height[-1]检索字符串的英寸部分,这将获取最后一个字符。但是一英尺有12英寸,所以如果一个球员是'6-12',你会错误地把它理解为6'2“。你知道吗

更好的解决方案是拆分连字符('-')上的字符串,并以这种方式分隔值。下面是一种使用列表理解的方法。你知道吗

import pandas as pd

# read data
df = pd.read_csv('Desktop/player_data.csv')

# drop rows with no height data
df = df.dropna(subset=['height'])     

# split the strings
df.height = [s.split('-') for s in df.height]
# convert to inches
df.height = [float(value[0])*12 + float(value[1]) for value in df.height]

# write data
df.to_csv('Desktop/player_data_updated.csv', index=False)

另外,当您将csv文件读入Python时,您不是在处理该文件本身,而是将其版本保存到内存中。csv文件将保持不变,除非您在最后再次将其保存到文件中。你知道吗

相关问题 更多 >