熊猫过滤器不起作用

2024-06-16 09:55:19 发布

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

我正在尝试创建一个新的df作为现有df的子集,使用:

filtered_df = df[((df.col == "Developing") | (df.col == "Ineffective") & (df.col_16 == "Developing") | (df.col_16== "Ineffective"))]

但这只是返回现有的df,没有应用任何过滤。在

我也试过:

^{pr2}$

另外,我还尝试分别为or和{}分别关闭|和{},但这会产生一个错误,告诉我使用|或{}。在

返回相同的结果

我的数据通常如下:

ID    loc  col         col_16      col_17    col_18
4568  12P  Effective   Ineffective Effective Developing
8521  02F  Ineffective Developing  Effective Highly Effective

期望的输出是df的过滤版本,其中只满足我指定的条件(col和col_16都表示“正在开发”或“无效”)。对于示例数据,只返回第二行。在


Tags: or数据版本iddf错误colloc
2条回答

您可以使用loc来分割数据。假设您的原始数据集与您列出的数据集相同,并且存储为df,那么首先创建一个包含要过滤的单词的列表。在

content_to_filter_by = ['Developing','Ineffective']

new_df = df.loc[(df['col'].isin(content_to_filter_by))&(df['col_16'].isin(content_to_filter_by)),:].copy()

有关使用loc和位于here的其他数据帧切片器的文档。在

您似乎缺少了一组将or语句分组在一起的括号:

试试这个:

filtered_df = df[(((df['col'] == "Developing") | (df['col'] == "Ineffective")) & ((df['col_16'] == "Developing") | (df['col_16'] == "Ineffective")))]

相关问题 更多 >