python - 根据其他数据框更改数据框中的值
问题描述
我有两个数据集如下
df1 = pd.DataFrame(np.array([[10, 20, 30, 40],
[11, 21, 31, 41]]), columns = ['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.array([0, 1, 0, 1]).reshape(1, -1), columns = ['A', 'B', 'C', 'D'])
我想要的是;如果 的 任何一项df2
大于0.5
,则在运行代码df1
后将是0
df1
print(df)
A B C D
10 0 30 0
11 0 31 0
我尝试使用
df1[df2>= 0.5] = 0
解决方案
由于两个数据帧的列数相同,因此where()
pandas 数据帧中的方法可以完成工作。IE
>>> df1.where(df2 < 0.5)
A B C D
0 10.0 NaN 30.0 NaN
1 NaN NaN NaN NaN
默认情况下,如果条件False
在where()
方法中评估为,则位置将替换为NaN
but not inplace
。我们可以通过将other
参数从默认值更改为0
并在我们设置的地方进行更改来更改它inplace=True
。
>>> df1.where(df2 < 0.5, other=0, inplace=True)
>>> df1
A B C D
0 10 0 30 0
1 0 0 0 0
推荐阅读
- web - 命名子域的正确方法是什么?
- sql-server - 如何将文件夹中的最新文件提供给集成服务中的平面文件源
- python - 如何同时下载多个文件并为每个完成触发特定操作?
- intellij-idea - 在长方法中查找东西(Intellij idea IDE)
- c# - C# 启动的线程多于预期
- react-native - 在 React Native 应用程序中预加载/预填充 PouchDB
- c++ - C++ 中正则表达式的特殊字符问题
- redis - ELK 堆栈和 Redis。我可以停止清空数据库吗?
- ionic-framework - 如何通过单击在ionic2中打开的相机上的后退按钮导航到页面
- python - ValueError: steps=None 仅对基于 keras.utils.Sequence 类的生成器有效