将一串数字转换为十六进制并返回到dec pandas python [英] Converting a string of numbers to hex and back to dec pandas python

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

问题描述

我目前有一串数据是通过csv文件中的数据进行过滤后检索到的。最终我不得不对数据进行一些过滤,但是我有与列表,数据框或数组相同的数字。我只需要将字符串中的数字转换为十六进制数,然后取十六进制数的前8个数字,并将其转换为字符串中每个元素的十进制数。最后,我还需要转换同一个十六进制的最后8个字符,然后再转换为字符串中的每个值。



我无法提供片段,因为它是敏感数据,但这里是一个例子。

我基本上有像这样的东西

 >>> list_A 

[52894036,78893201,45790373]

如果我将它转换为一个数据框并调用 df.dtypes ,它表示 dtype:object ,我可以将列A的值转换为bool ,int或字符串,但dtype始终是一个对象。

无论它是一个函数还是一个简单的循环都无关紧要。我一直在尝试很多方法,无法达到我需要的结果。但最终数据是从不同的csv文件中获取的,并且永远不会是相同的值或列表大小。

主要使用整数和浮点数,并且没有我知道的十六进制的特定功能,但可以使用 apply 来访问标准Python转换函数,如 hex 和 int

  df = pd .DataFrame({'a':[52894036999,78893201999,45790373999]})
df ['b'] = df ['a']。apply(hex)
df ['c'] = df ['b']。apply(int,base = 0)

结果:

  abc 
0 52894036999 0xc50baf407 52894036999
1 78893201999 0x125e66ba4f 78893201999
2 45790373999 0xaa951a86f 45790373999

请注意,此答案适用于Python 3.对于Python 2,您可能需要去掉列 bwi th str [: - 1]


I currently have a string of values which I retrieved after filtering through data from a csv file. ultimately I had to do some filtering of the data but I have the same numbers as a list, dataframe, or array. I just need to take the numbers in the string and convert them to hex and then take the first 8 numbers of the hex and convert that to dec for each element in the string. Lastly I also need to convert the last 8 of the same hex and then to dec as well for each value in the string.

I cannot provide a snippet because it is sensitive data, but here is an example.

I basically have something like this

>>> list_A

[52894036, 78893201, 45790373]

If I convert it to a dataframe and call df.dtypes, it says dtype: object and I can convert the values of Column A to bool, int, or string, but the dtype is always an object.

It does not matter whether it is a function, or just a simple loop. I have been trying many methods and am unable to attain the results I need. But ultimately the data is taken from different csv files and will never be the same values or list size.

解决方案

Pandas is designed to work primarily with integers and floats, with no particular facilities for hexadecimal that I know of, but you can use apply to access standard python conversion functions like hex and int:

df=pd.DataFrame({ 'a':[52894036999, 78893201999, 45790373999] })
df['b'] = df['a'].apply( hex )
df['c'] = df['b'].apply( int, base=0 )

Results:

             a             b            c
0  52894036999   0xc50baf407  52894036999
1  78893201999  0x125e66ba4f  78893201999
2  45790373999   0xaa951a86f  45790373999

Note that this answer is for Python 3. For Python 2 you may need to strip off the trailing "L" in column "b" with str[:-1].

这篇关于将一串数字转换为十六进制并返回到dec pandas python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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