python - 如何根据列值删除行,其中某些行的列值是另一行的子集?

标签 python python-3.x pandas

假设我有一个dataframe df as:-

index company  url                          address 
 0     A .    www.abc.contact.com         16D Bayberry Rd, New Bedford, MA, 02740, USA
 1     A .    www.abc.contact.com .       MA, USA
 2     A .    www.abc.about.com .         USA
 3     B .    www.pqr.com .               New Bedford, MA, USA
 4     B.     www.pqr.com/about .         MA, USA

我想从 dataframe 中删除所有行,其中 address 是另一个地址的子集并且公司是相同的。例如,我想要以上 5 行中的这两行。

index  company  url                          address 
 0     A .    www.abc.contact.com         16D Bayberry Rd, New Bedford, MA, 02740, USA
 3     B .    www.pqr.com .               New Bedford, MA, USA

最佳答案

也许这不是最佳解决方案,但它可以在这个小数据框上工作:

EDIT 添加了对公司名称的检查,假设我们删除了标点符号

df = pd.DataFrame({"company": ['A', 'A', 'A', 'B', 'B'],
                   "address": ['16D Bayberry Rd, New Bedford, MA, 02740, USA',
                               'MA, USA',
                               'USA',
                               'New Bedford, MA, USA',
                               'MA, USA']})
# Splitting addresses by column and making sets from every address to use "issubset" later
addresses = list(df['address'].apply(lambda x: set(x.split(', '))).values)
companies = list(df['company'].values)

rows_to_drop = []  # Storing row indexes to drop here
# Iterating by every address
for i, (address, company) in enumerate(zip(addresses, companies)):
    # Iteraing by the remaining addresses
    rem_addr = addresses[:i] + addresses[(i + 1):]
    rem_comp = companies[:i] + companies[(i + 1):]

    for other_addr, other_comp in zip(rem_addr, rem_comp):
        # If address is a subset of another address, add it to drop
        if address.issubset(other_addr) and company == other_comp:
            rows_to_drop.append(i)
            break

df = df.drop(rows_to_drop)
print(df)

company address
0   A   16D Bayberry Rd, New Bedford, MA, 02740, USA
3   B   New Bedford, MA, USA

关于python - 如何根据列值删除行,其中某些行的列值是另一行的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51686929/

相关文章:

python - 如何用字符串作为 x 轴值绘制两个图

python - 使用命令行参数在 C++ 中运行 python .py 文件

python - 如何将 numpy 的整数数组索引应用于 ndarray-s 和 python 列表?

Python/ Pandas : Eliminate for Loop using 2 DataFrames

python - 计算时间序列中连续二进制指标的数量

python - 在 Python 中打印 C 字符串

python - 为什么在 python 中使用已知数组初始化函数内的参数也会更改数组的值?

python-3.x - 在 AWS lambda 中使用/tmp 目录有多安全?

Python Pandas 无法导入 QUOTE_MINIMAL

python - Pandas 忽略非数字值