【问题标题】:Why are items in a pandas column, not in the pandas column that they're in?为什么项目在 pandas 列中,而不是它们所在的 pandas 列中?
【发布时间】:2020-10-24 08:23:42
【问题描述】:

如果我有一个随机值的数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,10, size=[5, 5]))

然后我选择任意一列并运行以下代码:

for x in df[0]:
    print(x in df[0])

我希望输出是:

True
True
True
True
True

但事实并非如此。它打印各种“真”和“假”。它似乎为 range(5) 中的项目打印“True”,否则为 False。我尝试将我的数据框更改为:

df = pd.DataFrame(np.random.randint(0,10, size=[6, 6]))

同样的代码为 range(6) 中的元素打印 True。如果我将条件更改为:

for x in df[0]:
    print(x in list(df[0]))

它按预期打印所有 True(无论数据框的大小如何)。谁能解释这是为什么?

【问题讨论】:

标签: python python-3.x pandas numpy dataframe


【解决方案1】:

df[0] 是熊猫系列对象<class 'pandas.core.series.Series'>。现在,x in df[0] 检查 series 中是否存在项目,检查 index 中是否存在 x

示例:

df = pd.DataFrame(np.arange(25).reshape(5,5))
#    0   1   2   3   4
#0   0   1   2   3   4
#1   5   6   7   8   9
#2  10  11  12  13  14
#3  15  16  17  18  19
#4  20  21  22  23  24

print(10 in df[0])
#False

但是,list(df[0]) 返回 pandas 系列值的列表(类似地,df[0].valuesdf[0].to_numpy()set(df[0]) 都是值)并且x in list(df[0])valuesx 是否存在/strong>。

print(10 in list(df[0]))
#True
print(10 in set(df[0]))
#True
print(10 in df[0].values)
#True
print(10 in df[0].to_numpy())
#True

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2019-06-02
    • 2017-12-24
    • 1970-01-01
    • 2023-01-25
    • 2013-05-22
    • 2018-02-23
    • 2016-01-18
    • 2017-05-13
    相关资源
    最近更新 更多