将pandas dataframe列从十六进制字符串转换为int [英] convert pandas dataframe column from hex string to int

查看:2004
本文介绍了将pandas dataframe列从十六进制字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的数据框,我想避免遍历每一行,并希望将整列从十六进制字符串转换为int。它不会使用astype正确处理字符串,但对单个条目没有问题。有没有办法告诉astype数据类型是基数16?

I have a very large dataframe that I would like to avoid iterating through every single row and want to convert the entire column from hex string to int. It doesn't process the string correctly with astype but has no problems with a single entry. Is there a way to tell astype the datatype is base 16?

IN:
import pandas as pd
df = pd.DataFrame(['1C8','0C3'], columns=['Command0'])
df['Command0'].astype(int)
OUT:
ValueError: invalid literal for int() with base10: '1C8'

这有效,但要避免行迭代。

This works but want to avoid row iteration.

for index, row in df.iterrows():
    print(row['Command0'])

我正在从CSV pd.read_csv(open_csv, nrows = 20)所以如果有一种方法可以读取它,并明确地告诉它格式是什么,那么这将是更好!

I'm reading this in from a CSV pd.read_csv(open_csv, nrows=20) so if there is a way to read it in and explicitly tell it what the format is then that would be even better!

推荐答案

您可以使用 apply

df.Command0.apply(lambda x: int(x, 16))
>>>
0    456
1    195
Name: Command0, dtype: int64

您可以使用转换器参数 pd.read_csv 调用

df = pd.read_csv("path.txt", converters={"Command0": lambda x: int(x, 16)})

这篇关于将pandas dataframe列从十六进制字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆