Pandas: python pandas.Series.isin 大小写不敏感的使用说明
在本文中,我们将介绍Pandas中pandas.Series.isin()函数的使用,以及如何使其大小写不敏感。
阅读更多:Pandas 教程
pandas.Series.isin()介绍
pandas.Series.isin()函数用于检查一个数据序列中的每一个元素是否在另一个序列中出现过,并返回一个布尔型序列。它的一般形式为:
pandas.Series.isin(values)
其中,values是要检查的元素序列,可以是列表、元组、集合或Series类型。
例如:
import pandas as pd
a = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = pd.Series([2, 4, 6, 8])
print(a.isin(b))
输出为:
0 False
1 True
2 False
3 True
4 False
5 True
6 False
7 True
8 False
dtype: bool
pandas.Series.isin()大小写不敏感
默认情况下,pandas.Series.isin()函数是大小写敏感的。也就是说,如果检查的元素序列中出现了大写字母,那么元素序列和原数据序列中的小写字母是不匹配的。例如:
a = pd.Series(["apple", "banana", "Orange", "Pineapple"])
b = pd.Series(["apple", "orange"])
print(a.isin(b))
输出为:
0 True
1 False
2 False
3 False
dtype: bool
可以看到,虽然元素序列中包含了”orange”(小写),但是原数据序列中有一个”Orange”(大写),导致不匹配。这时,我们就需要使用参数进行大小写不敏感的匹配。
我们需要用到str.lower()函数将数据序列中的所有字符串转为小写:
a = pd.Series(["apple", "banana", "Orange", "Pineapple"])
b = pd.Series(["apple", "orange"])
print(a.str.lower().isin(b.str.lower()))
输出为:
0 True
1 False
2 True
3 False
dtype: bool
这里,a和b序列都使用了str.lower()函数,将所有字符串转为小写,然后再执行isin()函数进行匹配。这样就能够大小写不敏感地进行匹配了。
pandas.Series.isin()参数介绍
除了大小写敏感参数之外,pandas.Series.isin()函数还有其他一些参数可以使用。这里我们进行简单介绍。
invert参数
invert参数用于控制查询结果的逆向。默认情况下,返回的是元素序列中出现在原数据序列中的元素所在的布尔型序列。如果设置invert=True,那么返回的就是没有出现在原数据序列中的元素所在的布尔型序列。例如:
a = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = pd.Series([2, 4, 6, 8])
print(a.isin(b, invert=True))
输出为:
0 True
1 False
2 True
3 False
4 True
5 False
6 True
7 False
8 True
dtype: bool
这里,invert=True表示返回不在b中的元素。
na_action参数
na_action参数用于控制空值处理:默认情况下,空值的处理方式是不参与任何匹配,直接返回False。如果设置na_action=’ignore’,那么空值将被视为匹配成功。例如:
a = pd.Series(["apple", "banana", "orange", pd.NA])
b = pd.Series(["ORANGE", pd.NA])
print(a.isin(b, na_action='ignore'))
输出为:
0 False
1 False
2 True
3 True
dtype: bool
这里,空值被视为匹配成功,所以第4个元素在元素序列中。
总结
在Pandas中,pandas.Series.isin()函数是非常实用的功能。在进行元素匹配时,可以使用大小写不敏感等参数,提高匹配的准确性和灵活性。
需要注意的是,在使用大小写不敏感匹配时,要使用str.lower()函数将所有字符串转为小写形式进行匹配。同时,在处理空值时,要注意使用na_action参数,设置空值的处理方式。