如何在以数字开头的字符串前面加上数据帧中同一行的字符串?

Bot*_*t75 2 python dataframe pandas

我有以下数据框(df):

col_1      col_2 col_3 col_4
sample_001 fjsah AB    11-110
sample_002 dfshb CD    20-210
sample_003 fsvhb EF    N3-303
sample_004 dfbkk GH    Q4-444
sample_005 gnddl IJ    55-005
Run Code Online (Sandbox Code Playgroud)

仅当字符串以数字开头时,我才想将字符串添加col_3到相应的字符串中,如下所示:col_4col_4df

col_1      col_2 col_3 col_4
sample_001 fjsah AB    AB11-110
sample_002 dfshb CD    CD20-210
sample_003 fsvhb EF    N3-303
sample_004 dfbkk GH    Q4-444
sample_005 gnddl IJ    IJ55-005
Run Code Online (Sandbox Code Playgroud)

我能够识别哪些col_4字符串以数字开头:

for n in df['col_4']:
    if n[0].isdigit():
        print(n)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在 for 循环中进行“选择性合并”

The*_*Guy 5

您可以用来Series.str[0].str.isdigit()创建一系列布尔值,指示每行中的第一个字符是否是数字,并且您可以使用此掩码来.loc修改值:

df.loc[df['col_4'].str[0].str.isdigit(), 'col_4'] = df['col_3']+df['col_4']

# df
        col_1  col_2 col_3     col_4
0  sample_001  fjsah    AB  AB11-110
1  sample_002  dfshb    CD  CD20-210
2  sample_003  fsvhb    EF    N3-303
3  sample_004  dfbkk    GH    Q4-444
4  sample_005  gnddl    IJ  IJ55-005
Run Code Online (Sandbox Code Playgroud)