简体   繁体   English

Python如何将float转换为十六进制到十进制

[英]Python How to convert a float as hex to decimal

I've read in some data from a csv file with pandas. 我已经从带有pandas的csv文件中读取了一些数据。 The data is incomplete and therefore contains many nan values. 数据不完整,因此包含许多纳米值。 I want to add a column to the data which converts the hex values to decimal values. 我想在数据中添加一列,将十六进制值转换为十进制值。 Unfortunately, the column with the hex values are all read as floats, not strings because they just happen to have those values. 不幸的是,具有十六进制值的列都被读取为浮点数,而不是字符串,因为它们恰好具有这些值。 Example data 示例数据

   val
0 20.0
1  nan
2 20.0

The simple way to convert a hex to decimal in python seems to be: int('20.0',16) , which should yield 32 . 在python中将十六进制转换为十进制的简单方法似乎是: int('20.0',16) ,它应该产生32

However, since this is pandas I cannot convert the values to int, or at least I keep getting an error stating that. 但是,由于这是pandas,我无法将值转换为int,或者至少我不断收到错误说明。 My current code is: 我目前的代码是:

df['valdec'] = np.where(np.isnan(df['val']), 
                    df['val'], 
                    int(df['val'].astype(int).astype(str), 16))

This fails with the error: 这失败并出现错误:

ValueError: Cannot convert NA to integer ValueError:无法将NA转换为整数

without the astype(int) the value is "20.0" which cannot be converted. 如果没有astype(int)则值为"20.0" ,无法转换。 Is there another way to interpret a float value as a hex value and convert to decimal when working with pandas dataframe? 还有另一种方法可以将浮点值解释为十六进制值,并在使用pandas数据帧时转换为十进制吗?

You can mask the rows of interest and double cast and call apply : 您可以屏蔽感兴趣的行并进行双重投射并调用apply

In [126]:
df['valdec'] = df['val'].dropna().astype(int).astype(str).apply(lambda x: int(x, 16))
df

Out[126]:
    val  valdec
0  20.0    32.0
1   NaN     NaN
2  20.0    32.0

So firstly we call dropna to remove the NaN , this allows us to cast to int using .astype(int) then convert to str by calling .astype(str) . 所以,首先我们称之为dropna删除NaN ,这让我们投来int使用.astype(int)然后将转换为str调用.astype(str)

We then call apply on this to convert to hex and assign the result of all this to the new column 然后我们调用apply来转换为十六进制并将所有这些结果分配给新列

Note that the dtype of the new column will be float as the presence of NaN enforces this, you won't be able to have a mixture of int s and float s 请注意,新列的dtype将为float因为NaN的存在强制执行此操作,您将无法混合使用intfloat s

As pointed out by @jasonharper, casting to int here will lose any fractional part so a higher precision method would be to use float.fromhex : 正如@jasonharper所指出的那样,在这里转换为int将丢失任何小数部分,因此使用float.fromhex的更高精度方法:

In [128]:
df['valdec'] = df['val'].astype(str).dropna().apply(lambda x: float.fromhex(x))
df

Out[128]:
    val  valdec
0  20.0    32.0
1   NaN     NaN
2  20.0    32.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM