【问题标题】:How to extract a particular bits of a specific column of Python pandas dataframe如何提取 Python pandas 数据帧特定列的特定位
【发布时间】:2019-08-12 04:02:04
【问题描述】:

对于熊猫数据框的特定列, 该列实际上是将 16 位数据转换为 BCD。 我只想提取特定行的第 14-8 位并转换为 BCD。 下面的公式适用于如下的小数据框。

df=pd.DataFrame({'Value':[128,128,436,465], 'Minutes':[1280,16384,1792,1536] })

df['Minutes_1']=df.Minutes.apply(int).apply(bin).str[2:].str[:-8].apply(int, base=2)
df

但是当我申请时

df['Minutes_1']=df.Minutes.apply(int).apply(bin).str[2:].str[:-8].apply(int, base=2)

对于 688126 行的更大数据框,我收到一条错误消息

int() 的无效字面量为 2:''

Note:  Few values of the row are 
0, 256,512,768,1024,1280,1536,1792,2048,2304,4096,4352,4608,4864,
5120,5276,5632,5888,6144,6400,8192,8448,8704,8960,9216,9472,9728,9984,10240,10496,12288,
12544,12800,13056,13312,13568,13824,14080,14336,14592,16384,16640,16896,17152,17408,17920,
18176,18432,18688,20480,20736,20992,21248,21504,21760,22016,22272,22528,22784

错误如下

ValueError Traceback(最近一次调用最后一次) 在 1 df.LO_TIME_0_J2_0 ----> 2 df['Minutes_1']=df.LO_TIME_0_J2_0.apply(int).apply(bin).str[2:].str[:-8].apply(int, base=2) 3 df.LO_TIME_0_J2_0

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 3192 其他: 第3193章 -> 3194 映射 = lib.map_infer(值,f,convert=convert_dtype) 3195 3196 if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in (x) 第3179章 3180 如果 kwds 或 args 而不是 isinstance(func, np.ufunc): -> 3181 f = lambda x: func(x, *args, **kwds) 3182 其他: 第3183章

ValueError: int() 以 2 为基数的无效文字:''

请帮忙

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您有一个值 0,因此当您将此值转换为 bin 时,0 变为 0b0,因此提取 str[2:].str[:-8] 您没有任何价值。

    我建议您在提取之间应用 zfill(16) 以填充 0:

    df['Minutes_1'] = df.Minutes.apply(int).apply(bin).str[2:].str.zfill(16).str[:-8].apply(int, base=2)
    

    也许使用 astype 比 apply(int) 快:


    df['Minutes_1'] = df.Minutes.astype(int).apply(bin).str[2:].str.zfill(16).str[:-8].apply(int, base=2)
    

    例子:

    df = pd.DataFrame( {'Minutes': [1280, 16384, 1792, 1536, 0, 256]})                                    
    df['Minutes_1'] = df.Minutes.apply(int).apply(bin).str[2:].str.zfill(16).str[:-8].apply(int, base=2)  
    

    输出:

       Minutes  Minutes_1  
    0     1280          5  
    1    16384         64  
    2     1792          7  
    3     1536          6  
    4        0          0  
    5      256          1  
    

    没有zfill,就会报错:

    ValueError: invalid literal for int() with base 2: ''

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      相关资源
      最近更新 更多