如何基于python中另一个数据帧中的值更改数据帧中的字段

2024-10-04 05:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

工作上的变化意味着我们旧的部门号码将不再使用,我们将在下个月使用新的部门号码。然而;我们仍然需要跟踪旧数据的旧部门名称-部门编号不会追溯更改

我正在使用两种不同的电子表格。一个是当前部门信息,另一个是从旧部门号到新部门号的人行横道

我需要做的是获取旧部门编号(成本中心和成本中心名称)的数据,并根据人行横道电子表格将旧部门编号更新为新部门编号,然后将这些行添加回原始电子表格

## Crosswalk
import pandas as pd

## Read in the ScorecardDepartments
## Set index to False
ambDF = pd.read_excel('ScorecardDepartments.xlsx','Departments',index=False)

crossDF = pd.read_excel('Crosswalk.xlsx',index=False)

## Only select rows that have departments in the Scorecard
ambDF = ambDF.loc[ambDF['Include in Scorecard'] == 'Y']

## Set Column Dept to int
pd.to_numeric(ambDF['Dept'])

ambDF = ambDF.sort_values(by=['Dept'])
crossDF = crossDF.sort_values(by=['Dept'])
## Change Crosswalk Dept column to a list
## to use in comparison
Departments = crossDF['Dept'].tolist()

## Create a new dataframe with just the 
## the dept information 
changeRows = ambDF.loc[ambDF['Dept'].isin(Departments)]

## Join the two dataframes
frames = [ambDF,changeRows]
result = pd.concat(frames,sort=True)

result.to_excel('tmp.xlsx')

更新:我将两个数据框连接在一起,但这只给了我一个大数据框,没有我需要的changeRows数据框中的列。此外,列的顺序也不正确


Tags: theto数据infalseindexexcel编号