python - 为什么 Pandas Series.isin 适用于字符串而不适用于数字?

标签 python pandas

简单的例子:

>>> df = pd.DataFrame(
         columns=['x', 'y', 'z'],
         data=np.array([
             ['a', 1, 'foo'],
             ['b', 2, 'bar'],
             ['c', 3, 'biz'],
             ['d', 99, 'baz'] ]))
>>> df
   x   y    z
0  a   1  foo
1  b   2  bar
2  c   3  biz
3  d  99  baz

>>> df[df.z.isin(['foo', 'biz'])]
   x  y    z
0  a  1  foo
2  c  3  biz

按预期工作!

但是,现在我尝试使用 y:

>>> df[df.y.isin([1,3])]
Empty DataFrame
Columns: [x, y, z]
Index: []

刚刚发生了什么?

我希望输出与上述 .z.isin(...) 示例相同的两行。

最佳答案

让我们看看问题的根源。它实际上是对 np.array 的调用。

np.array([['a', 1, 'foo'],
          ['b', 2, 'bar'],
          ['c', 3, 'biz'],
          ['d', 99, 'baz']])

这实际上是将整数强制转换为字符串:

array([['a', '1', 'foo'],
       ['b', '2', 'bar'],
       ['c', '3', 'biz'],
       ['d', '99', 'baz']], dtype='<U3')

请注意,由于类型强制,第二列全是字符串。 OTOH,如果您使用显式 dtype=object 初始化数组,则会保留各个类型:

data = np.array([['a', 1, 'foo'],
                 ['b', 2, 'bar'],
                 ['c', 3, 'biz'],
                 ['d', 99, 'baz']], dtype=object)

df = pd.DataFrame(columns=['x', 'y', 'z'], data=data)
df.y.isin([1,3])

0     True
1    False
2     True
3    False
Name: y, dtype: bool

或者,更好的是,传递一个异构的列表列表(不转换为数组)。

df = pd.DataFrame(data=[['a', 1, 'foo'],
                        ['b', 2, 'bar'],
                        ['c', 3, 'biz'],
                        ['d', 99, 'baz']], 
                  columns=list('xyz'))
df.y.isin([1,3])

0     True
1    False
2     True
3    False
Name: y, dtype: bool

关于python - 为什么 Pandas Series.isin 适用于字符串而不适用于数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52978035/

相关文章:

python - Python 中的列表

python - 在没有 Spark 群集的情况下运行 Azure Databricks

python - 将整个数据框中的 NaN 值替换为其他值的平均值

python - Pandas 绘制 3 个变量的图

python - 使用 PyDrive 上传 XLSX 并将其转换为 Google Sheets

python - 使用 Python 将颜色图/渐变图应用于图像

python - 仅当特定值出现在 Pandas 的一列中时,Groupby 才会计数

python - 百分比格式的 XlsxWriter 错误

python - 从两列中创建单个数据框,每列包含列表

python - 在一组 Pandas 数据框中提取具有最大值的行