python - 从数据框中的文本列中选择唯一的组合

标签 python pandas numpy

我的数据集中有两列,如下所示。我想要的是从所有“喜欢”的组合中仅选择一种组合。对于这种情况,(orange,fruit) 和 (fruit,orange) 是等价的,所以我只需要其中之一。另外,现在水果已经映射到橙色,我不再需要任何水果了。所以基本上(水果,红色)会变成(橙色,红色)

C1      C2
orange  fruit
orange  color
orange  apple
apple   red
apple   fruit
fruit   red
fruit   apple
fruit   mango
fruit   orange

这是我在 Python 中尝试过的代码

# Convert data frame to set of tuples

l = []

for i,x in df.iterrows():
    l.append((x['C1'],x['C2']))

s_comb = set(l)

# Set of unique values from C1
s = set(list(df['C1']))

#Initialize x with first element of s
x = list(df['C1'])[0]
x=[x]

# Code for creating combinations

for i in s:
    if i not in x:
        for j in x:
            if (i,j) not in s_comb:
                x.append(i)

预期输出:

C1      C2
orange  fruit
orange  color
orange  apple
orange  red
orange  mango

目前代码花费的时间很长,并且我不确定代码输出的准确性。

最佳答案

对于问题的第一部分,您可以这样做:

df['C'] = df.apply(lambda x: (str(set(x[['C1', 'C2']]))), axis=1)
df = df.drop_duplicates(subset='C')[['C1', 'C2']] 

对于第二部分,您可以执行类似的操作:

df['Cmin'] = df.apply(lambda x: min(x[['C1', 'C2']]), axis=1)
df = df.drop_duplicates(subset='Cmin')[['C1', 'C2']] 

df['Cmax'] = df.apply(lambda x: max(x[['C1', 'C2']]), axis=1)
df = df.drop_duplicates(subset='Cmax')[['C1', 'C2']] 

关于python - 从数据框中的文本列中选择唯一的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56452389/

相关文章:

python - Python 中的简单 Mandelbrot 集

python - 在 python 中读取 json 值时出现无效参数错误

Python:如何在不知道 DST 是否生效的情况下将时区感知时间戳转换为 UTC

python - 检测数据框 Pandas 的所有列中的值是否为数字并将其删除

python - 如何优化三对角矩阵的特征值/向量计算

python - Jacobi theta函数导数的实现

python - 通过另一个 DataFrame 中的行将新列映射到 DataFrame

python - docker中的 flask : different relative import in Dockerfile build and docker-compose

python - 如何在 Pandas 中用重复数据填充行?

python - 对于两个数据帧,如何检索两个标签值的组合在一个数据帧中但不在另一个数据帧中的行