Pandas系列搞乱布尔人

2024-09-30 01:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python代码使用了一个名为data的数据框,其中有两个列/序列标记为'Id'和'Open',填充了int和booleans。 但是下面的代码

print(data['Id'][0])
print(data['Id'][1])
print(data['Open'][0])
print(data['Open'][1]) 
print(data['Id'][0]!=0)
print(data['Id'][1]!=0)
print(data['Open'][0]!=0)
print(data['Open'][1]!=0) 

给我这个输出:

0    0
0    1
Name: Id, dtype: int64
1    0
1    2
Name: Id, dtype: int64
0    1
0    1
Name: Open, dtype: float64
1    1
1    1
Name: Open, dtype: float64
0    False
0     True
Name: Id, dtype: bool
1    False
1     True
Name: Id, dtype: bool
0    True
0    True
Name: Open, dtype: bool
1    True
1    True
Name: Open, dtype: bool

考虑到http://pandas.pydata.org/pandas-docs/stable/dsintro.html 将列描述为系列,我应该能够使用数据['Id'][0]并读取int及其比较结果为零。
但是我在索引下读到了这对愚蠢的数字,而我肯定我的df中没有元组(我从两个csv中解析了它,其中只包含int或0/1)。 那么我的错误在哪里呢?我也试过iloc和loc,但结果是一样的。 请问,我对熊猫医生有什么误解?你知道吗

附属问题:我打印它是因为我的布尔索引有问题,因为我想用data=data[data[id]>;0&;data['open']==1]选择我的数据,但它一直失败。我以前试过用 列表理解

booleanopen=[True if i==1 else False for i in data['Id']] 
booleanId=[True if i>01 else False for i in data['Id']] 
booleanand=booleanopen&booleanId
data=data[booleanand]

但它连续崩溃,没有回溯或错误消息。电脑卡住了好几个小时。 (我想我不能用:

booleanopen=[true for i==1 in data['Id']] 

因为它会给出一个长度等于1的真数组,与上一个相反)


Tags: 数据代码nameinidfalsetruefor
1条回答
网友
1楼 · 发布于 2024-09-30 01:35:04

I should be able to use data['Id'][0] and read an int

data["Id"][0]表示“获取名为Id的列,并访问与索引0关联的部分数据”。如果有多行具有相同的索引,pandas将返回它们。例如:

>>> df = pd.DataFrame({"Id": pd.Series([10,20,30], index=[0,0,1])})
>>> df["Id"][0]
0    10
0    20
Name: Id, dtype: int64
>>> df["Id"][1]
30

虽然你因为某种原因没有展示你的身体,但我很确定这就是发生的事情。您必须研究它是如何构造的,以找出原因(如果索引当前不包含任何信息,则始终可以df = df.reset_index(drop=True)返回到“正常”索引)

至于另一个问题,“但是它一直失败”并不能用作错误报告,但可能您只是没有使用括号,正如文档所示:

>>> df["Open"] = [1,2,1]
>>> df[(df["Id"] > 20) & (df["Open"] == 1)]
   Id  Open
1  30     1
>>> df.loc[(df["Id"] > 20) & (df["Open"] == 1)]
   Id  Open
1  30     1

相关问题 更多 >

    热门问题