DataFrame对比新增列遇astype属性错误及长度不匹配问题求解决
问题分析与解决方案
首先咱们得揪出问题的核心:你混淆了行和列的索引方式,还有一个小拼写错误!
你写的df_comparing.iloc[0]是取第0行的数据,而不是第0列——这直接导致后续生成的布尔Series长度是DataFrame的列数,和你要新增列的行数完全不匹配,所以才会出现Length of values does not match the length of the index错误;另外第一个代码里的astpye是astype的拼写错误,这也是触发Series object has no attribute 'astype'的原因。
要取第0列和第1列,应该用iloc[:, 0]和iloc[:, 1](:,表示选取所有行,后面的数字是列索引)。下面是两种正确的实现方式:
方法1:直接用布尔值转整数
import pandas as pd df_comparing = pd.read_excel(fName, sheet_name=0, index_col=None) df_compare_basis = pd.read_excel(readxl, index_col=None) # 修正列选取方式 + 拼写正确的astype df_comparing['Match'] = ( df_comparing.iloc[:, 0].isin(df_compare_basis['DataLineID']) | df_comparing.iloc[:, 1].isin(df_compare_basis['DataLineID']) ).astype(int)
方法2:用np.where实现
import pandas as pd import numpy as np df_comparing = pd.read_excel(fName, sheet_name=0, index_col=None) df_compare_basis = pd.read_excel(readxl, index_col=None) # 同样修正列选取,确保布尔数组长度和df行数一致 df_comparing['Match'] = np.where( df_comparing.iloc[:, 0].isin(df_compare_basis['DataLineID']) | df_comparing.iloc[:, 1].isin(df_compare_basis['DataLineID']), 1, 0 )
额外注意事项
- 确保
df_compare_basis['DataLineID']和df_comparing的第0、1列数据类型一致(比如都是字符串或数字),否则可能出现明明值存在但匹配失败的情况,可以用df['列名'].astype(str)统一类型后再做匹配。 - 如果
DataLineID有重复值,不影响isin()的判断,它只关心值是否存在。
内容的提问来源于stack exchange,提问作者cd-6
相关产品推荐
相关产品推荐

