我有一个这样的数据帧,

    A           length
0   648702831   9
1    26533315   8
2         366   3
3   354701058   9
4    25708239   8
5       70554   5
6     1574512   7
7        3975   4

现在,我想根据这样的条件创建一个列,
if ['length] == 9 or ['length] == 5:
   then ['new_col'] = First 5 Characters of ['A']

else if ['length] == 8 or ['length] == 4:
   then ['new_col'] = "0" & First 4 Characters of ['A']

else if ['length] == 7 or ['length] == 3:
   then ['new_col'] = "00" & First 3 Characters of ['A']

else
   ['new_col'] = ['A']

对于上述情况,我创建了以下逻辑进行检查(对于一个有10000行的文件,需要花费大量时间)
for i in df['length']:

    if i == 9 or i == 5:
        df['new_col'] = df['A'].astype(str).str[:5]
    elif i == 8 or i == 4:
        df['new_col'] = "0" + df['A'].astype(str).str[:4]

    elif i == 7 or i == 3:
        df['new_col'] = "00" + df['A'].astype(str).str[:3]

    else:
        df['new_col'] = df['A']

我得到以下输出,
    A          length   new_col
0   648702831   9      06487
1    26533315   8      02653
2         366   3      0366
3   354701058   9      03547
4     5708239   8      05708
5       70554   5      07055
6      1574512  7      01574
7         3975  4      03975


我需要这样的输出,
   A           length   new_col
0   648702831   9       64870
1    26533315   8       02653
2         366   3       00366
3   354701058   9       35470
4     5708239   8       05708
5       70554   5       70554
6      1574512  7       00157
7         3975  4       03975

我怎样才能做到这一点,而且如果有一种可以减少时间的方法,那就太好了。任何建议都将不胜感激。

最佳答案

zfill使用字符串切片。为了提高速度,使用列表理解。

m = {1: 5, 0: 4, 3: 3}
df['new_col'] = [
    x[:m.get(y % 4, 4)].zfill(5) for x, y in zip(df['A'].astype(str), df['length'])]

df
           A  length new_col
0  648702831       9   64870
1   26533315       8   02653
2        366       3   00366
3  354701058       9   35470
4   25708239       8   02570
5      70554       5   70554
6    1574512       7   00157
7       3975       4   03975

为了处理默认情况,我们可以在调用zfill时执行一些额外的检查:
df = df.append({'A' : 50, 'length': 2}, ignore_index=True)

m = {1: 5, 0: 4, 3: 3}

df['new_col'] = [
    x[:m.get(y % 4, 4)].zfill(5 if y % 4 in m else 0)
    for x, y in zip(df['A'].astype(str), df['length'])
]

df
           A  length new_col
0  648702831       9   64870
1   26533315       8   02653
2        366       3   00366
3  354701058       9   35470
4   25708239       8   02570
5      70554       5   70554
6    1574512       7   00157
7       3975       4   03975
8         50       2      50   # Default case.

08-20 01:35