各位,想要消除A列在B列出现过的重复值。
代码不能实现以下场景:A列出现金额12.78元5次,B列出现3次。
问题:下面的代码会全部消除A中的12.78元
需求:只想要消除A中该值3次,保留剩余2次。
ps:不能删除行,只转空值。
import pandas as pd
import numpy as np
# 读取Excel文件
df = pd.read_excel(r'D:\Learning\1.xlsx')
# 获取A列和B列
col_a = df['原币借方金额']
col_b = df['原币贷方金额']
# 判断A列中的值是否在B列中出现
is_in_b = col_a.isin(col_d)
# 将A列中与B列相等的值替换为NaN
df.loc[is_in_b, '原币借方金额'] = np.nan
# 将处理后的数据重新写入Excel文件
df.to_excel(r'D:\Learning\1.xlsx', index=False)
print('ok')
“Devil组”引证GPT后的撰写:
import pandas as pd
import numpy as np
# 读取Excel文件
df = pd.read_excel(r'D:\Learning\1.xlsx')
# 获取A列和B列
col_a = df['原币借方金额']
col_b = df['原币贷方金额']
# 获取A列中出现重复值的数量
duplicates_count = col_a.duplicated().sum()
# 判断A列中的值是否在B列中出现
is_in_b = col_a.isin(col_b)
# 用一个计数器记录当前已经替换了多少个重复值
count = 0
# 遍历A列中的每个值,如果它在B列中出现过,且替换的数量还没达到重复值的数量,
# 则将其替换为NaN,并将计数器加1
for i in range(len(col_a)):
if is_in_b[i] and count < duplicates_count:
df.at[i, '原币借方金额'] = np.nan
count += 1
# 将处理后的数据重新写入Excel文件
df.to_excel(r'D:\Learning\1.xlsx', index=False)
print('ok')