Python 熊猫系列从十六进制转换为ascii时出错
我有一个Python 熊猫系列从十六进制转换为ascii时出错,python,python-3.x,pandas,hex,Python,Python 3.x,Pandas,Hex,我有一个pandas.Series,具有多个str十六进制值: 74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78 00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55 74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,
pandas.Series
,具有多个str
十六进制值:
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
我正在尝试将十六进制转换为ascii,如下所示:
df['value'] = df['value'].apply(lambda x: codec.decode(x, 'hex')
我遇到了如下错误:
binascii.Error: decoding with 'hex' codec failed (Error: Odd-length string)
我预计某些行会出现这些错误,但需要更改可以转换为转换状态的值。在发生错误时,我怎么能对序列的值不做任何处理
预期产出:
this is my text to hex
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
this is my text to hex
this is my text to hex
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
使用int()
要简单得多
def fn(foo):
return int(foo, 16)
data = pd.Series(['74', '68', '69', '6d'])
data.apply(fn)
如果您想提供自己的转换器以允许其响应错误,可以提供函数而不是lambda。您对如何处理超出范围的值的要求不太清楚,因此我将仅展示一个基本示例:
def my_ascii_convert(char):
value = int(char, 16)
if 32 <= value < 128:
return chr(value)
else:
return char
df['value'] = df['value'].apply(my_ascii_convert)
def my_ascii_转换(字符):
value=int(字符,16)
如果32