python - pandas dataframe.apply -- 将十六进制字符串转换为整数

标签 python pandas dataframe

我对 python 和 pandas 都很陌生。我想知道如何将数据框元素从十六进制字符串输入转换为整数,我也遵循了以下提供的解决方案:convert pandas dataframe column from hex string to int

但是,还是不行。以下是我的代码:

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)

数据变量看起来像: data variable (type:DataFrame) 还有 spyder 中的控制台输出:enter image description here

错误发生在 data_numeric = data.apply(lambda x: int(x, 16)) 错误信息是

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,这不是我想要的。 有什么建议么?非常感谢!

最佳答案

假设我们有以下 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) 出于安全原因完成 - 如果您的某些列已经是数字数据类型

关于python - pandas dataframe.apply -- 将十六进制字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43899626/

相关文章:

python - 执行操作时恢复列

r - 循环 : how do I iterate through multiple columns of a dataframe? 的单向方差分析

python - 如何根据另一个数据框标准化 pandas 数据框

python - CVXPY 表达式未给出预期结果

python - 通过 _kMDItemUserTags 或 kMDItemOMUserTags 在 xattr 中使用多个关键字

python - 在按下特定键盘时等待 Matplotlib 图中的用户输入

python - 在python中基于Dataframe创建文件夹

python - DuckDuckGo 搜索返回 'List Index out of range'

pandas - 根据第一行的条件分组并应用 lambda - Pandas

python - Pandas 小数点后的位数