判断某一列数据是否在另一列中是数据处理时的常用操作,假设某dataframe中有两列数据
data = [['北京','上海','深圳','广州','杭州','南京','武汉','成都','苏州','青岛'],
['上海','南京','杭州','苏州','无锡','广州','深圳','东莞','香港','澳门']]
df = pd.DataFrame(data)
df = df.T
df.columns=['cities1','cities2']
假设要判断cities2列中的数据是否也在cities1列中,首先想到的应该是in 或者 not in。
df.cities2 in df.cities1
然而这显然是不行的
TypeError: 'Series' objects are mutable, thus they cannot be hashed
整列不行,那么自然想到的是df.apply方法
df[df.apply(lambda x: x.cities2 in x.cities1)]
很不幸,依然报错
AttributeError: 'Series' object has no attribute 'cities2'
这是由于apply默认axis=0,即是按列进行操作,而我们是需要按行操作,故得加上axis