我有一个格式如下的大数据帧:
| ID | A | B |
| -------- | ----------------- | ----------------------- |
| 0 | Tenure: Leasehold | Modern;Tenure: Leasehold|
| 1 | First Floor | Refurbished |
| 2 | NaN | Modern |
| 3 | First Floor | NaN |
在合并A列和B列之前,我想删除它们之间的冗余。所以我想检查A列中的值是否包含在B列中:如果是,A列应该取B列的值,如果不是,A列的值应该保持不变。
我尝试了以下lambda函数:
df['A'] = df['A'].apply(lambda x: df.B if df.A in df.B else df.A)
但我得到了这个错误:TypeError: 'Series' objects are mutable, thus they cannot be hashed
然后我尝试了np.where方法,如下所示:
df['A'] = np.where((df.A.values in df.B.values), df.B, df.A)
我可以运行代码,但它对所有列都返回false,所以我在DataFrame中没有得到任何修改。
如果我运行以下代码,它会返回True,所以我知道问题不是来自数据:
df.loc[0, 'A'] in df.loc[0, 'B']
我试着修改这个代码并这样使用它:
df['A'] = np.where((df.loc[:, 'A'] in df.loc[:, 'B']), df.B, df.A)
但后来我得到了与上面相同的TypeError。
我该如何解决这个问题?
df["A"] = df.apply(lambda x: x["B"] if x["A"] in x["B"] else x["A"], axis=1)
print(df)
打印:
ID A B
0 0 Modern;Tenure: Leasehold Modern;Tenure: Leasehold
1 1 First Floor Refurbished
编辑:处理NaN
s:
df["A"] = df.apply(
lambda x: x["B"]
if pd.notna(x["A"]) and pd.notna(x["B"]) and x["A"] in x["B"]
else x["A"],
axis=1,
)
print(df)
打印:
ID A B
0 0 Modern;Tenure: Leasehold Modern;Tenure: Leasehold
1 1 First Floor Refurbished
2 2 NaN Modern
3 3 First Floor NaN
如果要在"A"
:列中填充NaN
s
df.loc[df["A"].isna(), "A"] = df.loc[df["A"].isna(), "B"]
print(df)
打印:
ID A B
0 0 Modern;Tenure: Leasehold Modern;Tenure: Leasehold
1 1 First Floor Refurbished
2 2 Modern Modern
3 3 First Floor NaN
我会用zip做一个列表理解,当数据帧的大小增加时,zip与panda相比会很快应用:
df["A"] = [b if a in b else a for a,b in zip(df['A'],df['B'])]
print(df)
ID A B
0 0 Modern;Tenure: Leasehold Modern;Tenure: Leasehold
1 1 First Floor Refurbished