【问题标题】:How to fill an alphanumeric series in a column in a pandas dataframe?如何在熊猫数据框中的列中填充字母数字系列?
【发布时间】:2020-02-06 18:52:49
【问题描述】:

我有某些具有类似结构的 pandas 数据框

A    B    C

1    2    2
2    2    2 
...

我想创建一个名为 ID 的新列,并用一个看起来像这样的字母数字系列填充它

ID       A    B    C

GT001    1    2    2
GT002    2    2    2 
GT003    2    2    2 
...

我知道如何用字母或数字填充它,但我不知道是否有“熊猫本机”方法可以让我填充字母数字系列。最好的方法是什么?

【问题讨论】:

  • 试试'GT' + pd.Series(range(10)).astype(str).str.zfill(3)

标签: python python-3.x pandas alphanumeric


【解决方案1】:

欢迎来到 Stack Overflow!

如果你想要一个自定义 ID,那么你必须创建一个包含所需索引的列表:

list = []

for i in range(1, df.shape[0] + 1): # gets the length of the DataFrame.
    list.append(f'GT{i:03d}') # Using f-string for format and 03d for leading zeros.

df['ID'] = list

如果您想将其设置为索引,请执行df.set_index('ID', inplace=True)

【讨论】:

    【解决方案2】:
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'player': np.linspace(0,20,20)})
    
    n = 21
    data = ['GT' + '0'*(3-len(str(i))) + str(i) for i in range(1, n)]
    df['ID'] = data
    

    输出:

           player     ID
    0    0.000000  GT001
    1    1.052632  GT002
    2    2.105263  GT003
    3    3.157895  GT004
    4    4.210526  GT005
    5    5.263158  GT006
    6    6.315789  GT007
    7    7.368421  GT008
    8    8.421053  GT009
    9    9.473684  GT010
    10  10.526316  GT011
    11  11.578947  GT012
    12  12.631579  GT013
    13  13.684211  GT014
    14  14.736842  GT015
    15  15.789474  GT016
    16  16.842105  GT017
    17  17.894737  GT018
    18  18.947368  GT019
    19  20.000000  GT020
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2018-05-07
      • 2020-11-19
      • 1970-01-01
      • 2019-05-11
      • 2019-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多