在数据框中读取并转换某些列

2024-05-08 15:52:59 发布

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

我想用read\u csv读取数据帧。例如:

data = pd.read_csv("foo.txt", sep=' ', header=None, dtype={0:np.uint32, 1:np.uint32, 2:np.str})

除外foo.txt文件前两列是十六进制的。例如

ff462 44e44 house

可以使用int("ff462", 16)将十六进制值转换为int。如何读入数据以确保前两列转换为数据类型uint32?你知道吗


Tags: csvtxtnonereaddatafoonp读取数据
2条回答

您可以将数据作为字符串读入,然后将其转换为。。。你知道吗

data = pd.read_csv("foo.txt", sep=' ', header=None, dtype=str)
data.iloc[:, [0, 1]] = df.iloc[:, [0, 1]].apply(lambda x: int(x, base=16)).astype(np.uint32)

显然这是可行的(cf.here):

data['1'] = data.1.apply(lambda x: int(x,base=0) )
data['1'] = data['1'].astype(np.uint32)

相关问题 更多 >