![](/img/trans.png)
[英]How to check if a string value of one row is contained in the string value of another row in the same column in pandas dataframe
[英]How to check whether the string value of a Pandas Column is contained in the string value of another Pandas Column?
我有一个大的 dataframe 格式如下:
| 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 function:
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
:
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 做一个列表理解,与 pandas 相比,它会非常快,因为 dataframe 的大小增加:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.