convert pandas dataframe column from hex string to int

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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'])

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!

回答1:

You could use apply.

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

And you can do this with pd.read_csv call using the converters parameter:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!