Python Pandas如何测试作为类别数据类型的Pandas列之间的相等性



我有大型数据集,可以与python-panda交叉连接。两个数据集都加载在panda中,我将所有"object"列转换为"category"。问题是,我需要对各种"category"数据类型列执行pd.query((。当对"category"列执行此操作时,它会返回一个错误(我预计会出现这种情况,因为并非所有列都具有相同的值(例如,同时存在、同时存在或不存在的子集和超集(。然而,在pd.query((方法中,我可以通过df["col1"].astype("object"(转换每个对象,并针对另一个对象列进行测试。当比较";对象";类型,我的数据集的内存大小增长到GB,我遇到了MemoryError。是否有我不知道的东西可以让我测试两个或多个具有不同值范围的"类别"数据类型列之间的相等性?下面的示例代码:

import pandas as pd
df = pd.DataFrame({"c1":["a","b","c","d"],
"c2":["d","e","f","d"]})
print(df)
print()
df["c1"] = df["c1"].astype("category")
df["c2"] = df["c2"].astype("category")
### testing equality of category column dtypes
try : df.query("c1 == c2")
except: print("ERROR: we know this returns 'ValueError: unkown type object' bc comparing 'category' column dtypes ")
print()
dfObj = df.query("c1.astype('object') == c2.astype('object')")
print("NO ERROR because during comparions converted 'category' to 'object'!")
print(dfObj)

结果:

c1 c2
0  a  d
1  b  e
2  c  f
3  d  d
ERROR: we know this returns 'ValueError: unkown type object' bc comparing 'category' column dtypes 
NO ERROR because during comparions converted 'category' to 'object'!
c1 c2
3  d  d

您可以使用union_categoricals来执行您想要的操作。

然后比较您的两列,您的代码将如下所示:

from pandas.api.types import union_categoricals
union = union_categoricals([df.c1, df.c2]).categories
df['c1'] = df.c1.cat.set_categories(union)
df['c2'] = df.c2.cat.set_categories(union)
print (df.c1 == df.c2)
0    False
1    False
2    False
3     True

如果你需要更多详细信息,这是文档:

https://pandas.pydata.org/docs/reference/api/pandas.api.types.union_categoricals.html

这篇文章是这个问题的重复:

更新两个系列/列中的类别以进行比较

最新更新