【问题标题】:How to align a pandas Series into the same length? [duplicate]如何将熊猫系列对齐到相同的长度? [复制]
【发布时间】:2019-11-14 13:58:55
【问题描述】:

我有一个具有不同元素长度的系列,如下所示:1、222、33、4、55555、...

我想让它和 5 一样长,像这样:00001, 00222, 00033, 00004, 55555, ...

我该怎么做?谢谢,

【问题讨论】:

    标签: python pandas numpy series


    【解决方案1】:

    你可以使用zfill,假设你的元素是字符串:

    import pandas as pd
    
    s = pd.Series(data=['1', '222', '33', '4', '55555'])
    
    result = s.str.zfill(max(map(len, s)))
    print(result)
    

    输出

    0    00001
    1    00222
    2    00033
    3    00004
    4    55555
    dtype: object
    

    【讨论】:

      【解决方案2】:
      import pandas as pd
      
      df = pd.Series([0] * 5) 
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        df = pd.DataFrame([1, 222, 44, 55555], columns=['Val'])
        max_length = max(df['Val'].astype(str).str.len())
        df['SameLen'] = df['Val'].astype(str).map(lambda x: '0' * (max_length - len(x)) + x)
        

        输出:

            Val  SameLen
        0     1    00001 
        1   222    00222 
        2    44    00044 
        3 55555    55555 
        

        【讨论】:

          猜你喜欢
          • 2019-09-11
          • 2021-12-28
          • 1970-01-01
          • 1970-01-01
          • 2021-08-15
          • 2020-02-07
          • 2021-08-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多