将字典作为筛选条件去筛选 df2 将相同的数据进行保留
时间: 2024-03-16 19:41:40 浏览: 67
你可以使用 Pandas 的 Series 的 `map` 方法,将 DataFrame 中的某一列进行映射,然后根据映射结果进行筛选。具体步骤如下:
1. 将第二个 Excel 文件中的某一列(假设该列为“用户账号”列)取出,保存为一个 Series 对象。
2. 使用 `map` 方法,将该 Series 对象中的每个元素作为字典的键,得到一个新的 Series 对象,其中每个元素为对应的字典的值(即“姓名”列的内容)。
3. 根据映射后的 Series 对象与某个值(假设该值为“某个姓名”)进行比较,得到一个布尔型的 Series 对象,其中每个元素表示该行数据是否满足条件。
4. 根据上一步得到的布尔型 Series 对象,使用 DataFrame 的 `loc` 方法进行筛选,得到满足条件的行。
具体代码如下:
```python
import pandas as pd
# 读取第一个 Excel 文件,转换为字典
df1 = pd.read_excel(r"C:\Users\asus\Desktop\用户账号情况统计表.xlsx")
organization_user_dict = df1.set_index('用户账号')['姓名'].to_dict()
# 读取第二个 Excel 文件
df2 = pd.read_excel(r"C:\Users\asus\Desktop\人员分配企业岗位查询表.xlsx")
# 将“用户账号”列的内容映射为“姓名”列的内容
mapped_names = df2['用户账号'].map(organization_user_dict)
# 根据映射结果和某个姓名进行比较,得到布尔型 Series 对象
mask = (mapped_names == '某个姓名')
# 根据布尔型 Series 对象进行筛选
filtered_data = df2.loc[mask]
# 保留相同的数据
filtered_data.drop_duplicates(inplace=True)
# 打印筛选结果
print(filtered_data)
```
其中,“某个姓名”是你要筛选的条件值。注意,在筛选结束后,使用了 `drop_duplicates` 方法去除了重复的行。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)