Swe*_*abh 3 python subset pandas
我有来自 2 个不同数据框的 2 列。我想检查第 1 列是否是第 2 列的子集。
我正在使用以下代码:
set(col1).issubset(set(col2))
Run Code Online (Sandbox Code Playgroud)
问题在于,如果 col1 只有整数而 col2 既有整数又有字符串,则返回 false。发生这种情况是因为 col2 的元素被强制转换为字符串。例如,
set([376, 264, 365, 302]) &
set(['302', 'water', 'nist1950', '264', '365', '376'])
Run Code Online (Sandbox Code Playgroud)
我尝试使用isin来自熊猫。但是如果 col1 和 col2 是系列,那么这会给出一系列布尔值。我要True or False。
我该如何解决这个问题?有没有我错过的更简单的功能?
编辑 1
添加示例。
col1
0 365
1 376
2 302
3 264
Name: subject, dtype: int64
col2
0 nist1950
1 nist1950
2 water
3 water
4 376
5 376
6 302
7 302
8 365
9 365
10 264
11 264
12 376
13 376
Name: subject, dtype: object
Run Code Online (Sandbox Code Playgroud)
编辑 2
col1 和 col2 可以有整数、字符串、浮点数等。我不想对这些列中的内容进行任何预先判断。
您可以使用isinwithall检查您的所有col1元素是否都包含在col2. 要转换为数字,您可以使用pd.to_numeric:
s1 = pd.Series([376, 264, 365, 302])
s2 = pd.Series(['302', 'water', 'nist1950', '264', '365', '376'])
res = s1.isin(pd.to_numeric(s2, errors='coerce')).all()
In [213]: res
Out[213]: True
Run Code Online (Sandbox Code Playgroud)
更详细:
In [214]: pd.to_numeric(s2, errors='coerce')
Out[214]:
0 302
1 NaN
2 NaN
3 264
4 365
5 376
dtype: float64
In [215]: s1.isin(pd.to_numeric(s2, errors='coerce'))
Out[215]:
0 True
1 True
2 True
3 True
dtype: bool
Run Code Online (Sandbox Code Playgroud)
注意 pd.to_numeric与大熊猫版本适用>=0.17.0于以前的你cound使用convert_objects与convert_numeric=True
编辑
如果您更喜欢解决方案,set您也可以将您的第一组转换str为,然后将它们与您的代码进行比较:
s3 = set(map(str, s1))
In [234]: s3
Out[234]: {'264', '302', '365', '376'}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用issubsetfor s2:
In [235]: s3.issubset(s2)
Out[235]: True
Run Code Online (Sandbox Code Playgroud)
或为set(s2):
In [236]: s3.issubset(set(s2))
Out[236]: True
Run Code Online (Sandbox Code Playgroud)
编辑2
s1 = pd.Series(['376', '264', '365', '302'])
s4 = pd.Series(['nist1950', 'nist1950', 'water', 'water', '376', '376', '302', '302', '365', '365', '264', '264', '376', '376'])
In [263]: s1.astype(float).isin(pd.to_numeric(s4, errors='coerce')).all()
Out[263]: True
Run Code Online (Sandbox Code Playgroud)