【问题标题】:pandas series convert to ascii from hex with error熊猫系列从十六进制转换为 ascii 时出错
【发布时间】:2017-07-09 05:56:38
【问题描述】:

我有一个 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

【问题讨论】:

    标签: python python-3.x pandas hex


    【解决方案1】:

    如果您想提供自己的转换器以允许它响应错误,您可以提供一个函数而不是 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)
    

    【讨论】:

      【解决方案2】:

      使用int() 要简单得多

      def fn(foo):
          return int(foo, 16)
      
      data = pd.Series(['74', '68', '69', '6d'])
      data.apply(fn)
      

      【讨论】:

        猜你喜欢
        • 2018-12-06
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 1970-01-01
        • 2012-11-14
        • 2016-04-22
        相关资源
        最近更新 更多