循环中的Isin函数不能正常工作

2024-06-26 13:26:03 发布

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

我有一个数据帧

 X      Y

110     0
110     0
110     1
111     1
111     0
112     1
113     1
114     0

当我过滤datsframe使操作像len和sum一样正常工作时,就像这里一样

new = df.x.isin([110,111])
df[new]
len(df[new].y) = 5
sum(df[new].y) = 2

但是,当我在循环中调用isin函数时,它不能正常工作。你知道吗

我有第二个数据帧df0

col1 . col2

a     110,111
b     113
c     114,1114
d     267,118
e     956

我想在df0上迭代,像在这个循环中一样,执行len和sum操作,调用df0.col2中df.x元素的groupgr

for i in df0.index:
    gr = df0.get_value(i, 'col2')
    new = df.x.isin([gr])
    df_size = len(df[new].y)
    df_sum = sum(df[new].y)

问题是,在gr=110111组中,元素111被忽略

所以df_size=3,df_sum=1,应该是5和2


Tags: 数据函数元素dfnewsizelencol2
1条回答
网友
1楼 · 发布于 2024-06-26 13:26:03

请看第一个代码示例的第一行:

new = df.x.isin([110,111])

isin的参数是一个列表。你知道吗

然后看第二个代码示例中的df.x.isin([gr]),注意 如果gr是例如'111,112'(字符串),则[gr]包含 ['111,112'],即包含单个元素的列表。 你用方括号“包围”gr的事实并没有分裂gr。你知道吗

解决it问题的一个可能方法是将col2 方法如下:

df0.col2 = df0.col2.str.split(',')

使每个元素也包含一个列表(不是字符串)。你知道吗

然后将第二个代码示例更改为:

for _, row in df0.iterrows():
    new = df[df.x.isin(row.col2)]
    df_size = new.y.size
    df_sum = new.y.sum()
    print(row.col2, df_size, df_sum)

在最终版本中,将print替换为您想对其执行的任何操作 变量。你知道吗

相关问题 更多 >