代码之家  ›  专栏  ›  技术社区  ›  Raquel Feltrin

通过计数字符确定变量值的位置

  •  0
  • Raquel Feltrin  · 技术社区  · 2 年前

    我需要计算每个变量值在数据帧中的位置。例如,让我们使用这个数据框架:

    创建DataFrame

    data = {
        'ol': ['H_KXKnn1_01_p_lk0', 'H_KXKnn1_02_p_lk0', 'H_KXKnn1_03_p_lk0'],
        'nl': [12.01, 89.01, 25.01],
        'nol': ['Xn', 'Ln', 'Rn'],
        'nolp': [68, 70, 72],
        'nolxx': [0.0, 1.0, 5.0]
    }
    
    df = pd.DataFrame(data)
    

    我将此数据帧保存为.dat

    df.to_csv('your_file.dat', sep='\t', index=False)
    

    当我计算.dat文件中每个值字符开始和结束的位置时,我会得到:

    variable position (start,end)
    ol        (0,17)
    nl        (18,23)
    nol       (24,26)
    nolp      (27,29)
    nolxx     (30,33)
    

    我也在考虑“_”、“.”和空间作为字符。但是,当我运行这段代码来遍历每一列时:

    for col in df.columns:
        col_length = df[col].astype(str).apply(len).max() + df[col].astype(str).apply(lambda x: x.count('_') + x.count('.')).max()
        positions[col] = (current_pos, current_pos + col_length - 1)
        current_pos += col_length + 1
    
    positions_df = pd.DataFrame(list(positions.items()), columns=['Variable', 'Position'])
    

    它返回以下值:

      Variable    Position
          ol      (0, 20)
          nl     (22, 27)
         nol     (29, 30)
        nolp     (32, 33)
       nolxx     (35, 38)
    

    我不知道为什么它返回不同的数字/位置。欢迎任何帮助我如何做到这一点!非常感谢。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Mohsen_Fatemi    2 年前

    第一列中所有字符串的长度为 17 。您正在向其添加一个附加值,以使结果不同。既然你有3个 '_' 在字符串中,它变为17+3=20。

    df[col].astype(str).apply(lambda x: x.count('_') + x.count('.')
    

    以下是您的代码的修改版本,它产生的输出与您从第一个代码中获得的输出相同:

    positions = {}
    current_pos = 0
    
    for col in df.columns:
        col_length = df[col].astype(str).apply(len).max()
        positions[col] = (current_pos, current_pos + col_length)
        current_pos += col_length + 1
    
    positions_df = pd.DataFrame(list(positions.items()), columns=['Variable', 'Position'])
    

    输出如下:

     Variable  Position
    0       ol   (0, 17)
    1       nl  (18, 23)
    2      nol  (24, 26)
    3     nolp  (27, 29)
    4    nolxx  (30, 33)