python - 我可以使用布尔循环找到两个 df cols 相等的值然后设置 df1['col1'] = df2['col2']
问题描述
我必须找到df2 col1
等于的值df1 col1
,然后从同一行df1 col2
替换为。df2 col2
我已经尝试过.isin()
(可能不正确)和多个条件,即if (df1['col1'] == df2['col1']) & (df1['col3'] == 'x index')
i=0
for i in df1:
if df1['col1'].isin(df2['col1']):
df1['col2'] = df2['col2']
else df1['col1'].isin(df3):
df1['col2'] = df['col3']
i+=1
解决方案
请,如果您找到不使用循环的解决方案,它总是更好。在您的情况下,查找另一列中的行可以通过内部连接来解决。我希望这是一个可以解决您的问题的代码。
In [1]:
## Set the exemple with replicable code
import pandas as pd
cols = ['col1', 'col2']
data = [[100, 150],
[220, 240],
[80, 60]
]
df1 = pd.DataFrame(data=data, columns=cols).set_index('col1')
cols = ['col1', 'col2']
data = [[111, 0],
[220, 0],
[80, 0]
]
df2 = pd.DataFrame(data=data, columns=cols).set_index('col1')
## Get all the rows from df1 col1 that are in df2 col1
df_merge = df1.merge(df2, left_index=True, right_index=True, how='inner', suffixes=('_df1', '_df2'))
df_merge
Out [1]:
col2_df1 col2_df2
col1
220 240 0
80 60 0
然后做一个左连接将值添加col2 df2
到col2 df1
In [2]:
df1 = df1.merge(df_merge, how='left', left_index=True, right_index=True)
df1.drop(axis=1, columns=['col2', 'col2_df1'], inplace=True)
df1.rename(columns={'col2_df2': 'df2'}, inplace=True)
df1
Out [2]:
df2
col1
100 NaN
220 0.0
80 0.0
推荐阅读
- django - 在 django 媒体中保存图像文件而不是在 quill 编辑器中使用 base64?
- css - div 和垂直滚动条或垂直滚动 div 之间的填充
- continuous-integration - 使用 GitHub Actions 部署到 GCloud VM 实例
- visual-studio-code - Visual Studio Code:如何禁用“找不到 .NET Core SDK”
- python - 安装 Python 的 Mageck 包时无法修复 C 编译环境错误
- css - Bootstrap NavDropdown ClassName active 不存在,如何知道何时选择了下拉元素?
- python - 有没有办法在 Kivy 中创建 2D 难以处理的网格?
- iis - 应用程序托管在托管术语中的 w3wp.exe(进程内)或 application.exe/dotnet.exe(进程外)中的含义
- python - CSV 文件未正确写入 ByteString
- python - 规范化数据集以查找季节性和平均 python pandas