问题描述
我对 python 和 Pandas 都很陌生.我想知道如何将数据框元素从十六进制字符串输入转换为整数,我也遵循了以下提供的解决方案:将 Pandas 数据框列从十六进制字符串转换为 int
I am very new to both python and pandas. I would like to know how to convert dataframe elements from hex string input to integer number, also I have followed the solution provided by: convert pandas dataframe column from hex string to int
但是,它仍然无法正常工作.以下是我的代码:
However, it is still not working. The following is my code:
df = pd.read_csv(filename, delim_whitespace = True, header = None, usecols = range(7,23,2))
for i in range(num_frame):
skipheader = lineNum[header_padding + i*2]
data = df.iloc[skipheader:skipheader + 164:2]
data_numeric = data.apply(lambda x: int(x, 16))
dataframe.append(data)
数据变量看起来像:数据变量(类型:DataFrame)还有 spyder 中的控制台输出:在此处输入图像描述
the data variable looks like:data variable (type:DataFrame)also the console output in spyder:enter image description here
错误发生在 data_numeric = data.apply(lambda x: int(x, 16))
错误信息是
the error happens at data_numeric = data.apply(lambda x: int(x, 16))
and the error message is
TypeError: ("int() can't convert non-string with explicit base", u'occurred at index 7')
我也试过data_numeric = data.apply(pd.to_numeric, errors='coerce')
但是所有的十六进制数都变成了 NaN,这不是我想要的.有什么建议么?非常感谢提前!
I had also trydata_numeric = data.apply(pd.to_numeric, errors='coerce')
but all the hex number turn into NaN, which is not I want.Any suggestions? Thanks a lot in advance!!!
推荐答案
假设我们有以下 DF:
assume we have the following DF:
In [62]: df
Out[62]:
a b c
0 1C8 21 15F
1 0C3 B7 FFC
我们可以这样做:
In [64]: df = df.apply(lambda x: x.astype(str).map(lambda x: int(x, base=16)))
In [65]: df
Out[65]:
a b c
0 456 33 351
1 195 183 4092
In [66]: df.dtypes
Out[66]:
a int64
b int64
c int64
dtype: object
PS x.astype(str)
是出于安全原因完成的 - 如果您的某些列已经是数字 dtype
PS x.astype(str)
is done for security reasons - in case if some of your columns are already of numeric dtype
这篇关于pandas dataframe.apply -- 将十六进制字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!