Python Pandas -- 连接字符串 if 条件

Python Pandas -- Concatenate strings if condition

pd.DataFrame 中,我在 A 列中有字符串,其 len 等于 5 或​​ 6。如果单元格值 len(value) == 5 那么我需要连接字符串 '7' 到单元格值的开头。我目前正在尝试下面的代码,但似乎无法将 apply 与 inplace=True 参数一起使用。

 df[df['A'].str.len() == 5]['A'].apply(lambda x: '7' + str(x))

这将 return 列 - 但不会就地修改数据框...

你可以试试:

df['A'] = df.A.apply(lambda s: '7' + s if len(s) == 5 else s)