Python Pandas——如果有条件则连接字符串

标签 python pandas concatenation

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))

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

最佳答案

你可以试试:

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

关于Python Pandas——如果有条件则连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706449/

相关文章:

python - 根据 Pandas groupby() 结果删除行

python - 为什么 pandas 的 DataFrame 系列 mean() 失败,但 sum() 却没有,如何让它工作?

python - Pandas 堆叠条形图具有不同的形状

python - python函数字节码中的零是什么意思?

python - 如何使用 Cython 类型的内存 View 接受来自 Python 的字符串?

python - 如何在文件中写入 YAML 格式的数据?

Python PIL 在渲染文本时添加额外的字符

arrays - 如何连接两个字符串以创建变量名称

python - 如何将不同排名的列表连接成排名 0 的单个列表?

Excel VBA 宏 - 在循环中连接