在Python数据框架中是否有任何方法可以查看两列是否相同,但具有重命名的值?



例如,如果我有一个包含动物园中所有个体的大型数据框,并且有两列分别是Animal_Common_Name和Animal_Scientific_Name。我怀疑其中一个是多余的,因为一个特征完全由另一个特征决定,反之亦然。基本上是相同的特征,只是重命名了。

是否有函数选择了两个不同的列?

假设如下:

Animal_Common_Name  Animal_Scientific_Name
0               Lion            Panthera leo
1            Giraffe  Giraffa camelopardalis
2               Lion            Panthera leo

使用factorize转换为分类整数,然后比较是否所有值都相等:

(pd.factorize(df['Animal_Common_Name'])[0] == pd.factorize(df['Animal_Scientific_Name'])[0]).all()

输出:True

如果你想识别多个关系:

df[df.groupby('Animal_Scientific_Name')['Animal_Common_Name'].transform('nunique').ne(1)]

列名也一样

df['Animal_Common_Name'].equals(df['Animal_Scientific_Name'])

如果它们相同,则返回True,否则返回false。

可以使用pandas.Series.equals()方法。

例如:

import pandas as pd
data = {
'Column1': [1, 2, 3, 4],
'Column2': [1, 2, 3, 4],
'Column3': [5, 6, 7, 8]
}
df = pd.DataFrame(data)
# True
print(df['Column1'].equals(df['Column2']))
# False
print(df['Column1'].equals(df['Column3']))

查找自GeeksForGeeks

您可以使用pandas的矢量化操作来快速确定冗余。下面是一个例子:

import pandas as pd
# create a sample dataframe from some data
d = {'name1': ['Zebra', 'Lion', 'Seagull', 'Spider'],
'name2': ['Zebra', 'Lion', 'Bird', 'Insect']}
df = pd.DataFrame(data=d)
# create a new column for your test:
df['is_redundant'] = ''
# select your empty column where the redundancy exists:
df['is_redundant'][df['name1']==df['name2']] = 1
print(df)

name1   name2   is_redundant
0   Zebra   Zebra   1
1   Lion    Lion    1
2   Seagull Bird    
3   Spider  Insect  

然后您可以将空的部分替换为0或保留,这取决于您的应用程序。

相关内容

最新更新