python - Pandas Dataframe 用另一列中的值替换部分字符串
问题描述
我尝试用另一列中的值替换字符串时遇到替换问题。我想用 df['Length'] 替换'Length'。
df["Length"]= df["Length"].replace('Length', df['Length'], regex = True)
下面是我的数据
Input:
**Formula** **Length**
Length 5
Length+1.5 6
Length-2.5 5
Length 4
5 5
Expected Output:
**Formula** **Length**
5 5
6+1.5 6
5-2.5 5
4 4
5 5
但是,使用我上面使用的代码,它将替换我的整个单元格而不是仅替换 Length。我得到以下输出:我发现这是由于使用了 df['column'],如果我使用任何其他字符串,后面的偏移量(-1.5)将不会被替换。
**Formula** **Length**
5 5
6 6
5 5
4 4
5 5
我可以知道其他列的值是否有任何替换方法?
谢谢你。
解决方案
如果需要用另一列替换,请使用DataFrame.apply
:
df["Formula"]= df.apply(lambda x: x['Formula'].replace('Length', str(x['Length'])), axis=1)
print (df)
Formula Length
0 5 5
1 6+1.5 6
2 5-2.5 5
3 4 4
4 5 5
或列表理解:
df["Formula"]= [x.replace('Length', str(y)) for x, y in df[['Formula','Length']].to_numpy()]
推荐阅读
- javascript - Django AJAX 返回 undefined 而不是变量
- c# - 如何按2列对列表进行排序
- javascript - Rails:多步表单上的动态选择未保持选中状态
- javascript - 如何阻止蛇对角线移动?
- mongodb - MongoDB 3.6 如何将字符串转换为对象 ID
- java - 使用 Selenium 在视口内滚动到位于当前页面上的 Web 元素的最佳方法是什么
- ruby - Ruby - 混合命名参数和位置参数,为什么顺序很重要?
- python-3.x - 如何导入模块以便可以从任何目录访问它?
- php - 不应静态调用非静态方法 Illuminate\Database\Eloquent\Model::update()
- javascript - 如何在节点之间添加冲突..?