如何使用Python动态字符串过滤数据帧

2024-04-20 01:55:21 发布

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

数据帧

    PROJECT  CLUSTER_x  MARKET_x  CLUSTER_y  MARKET_y     Exist
0   P17      A          CHINA     C          CHINA        both
1   P18      P          INDIA     P          INDIA        both
2   P16      P          AMERICA   P          AMERICA      both
3   P19      P          INDIA     P          JAPAN        both

下面的代码工作得很好,输出为索引0和3

df_mismatched = df_common[ (df_common['MARKET_x'] != df_common['MARKET_y']) | (df_common['CLUSTER_x'] != df_common['CLUSTER_y']) ]

我们如何动态地建立这样的过滤标准?类似于下面的代码,这样下次就不需要硬编码了

str_common = '(df_common["MARKET_x"] != df_common["MARKET_y"]) | (df_common["CLUSTER_x"] != df_common["CLUSTER_y"])'
df_mismatched = df_common[str_common]

Tags: 数据代码projectdfcommonmarketexistcluster
1条回答
网友
1楼 · 发布于 2024-04-20 01:55:21

出于动态目的,可以在python中使用^{},如:

con = "(MARKET_x!=MARKET_y)|(CLUSTER_x!=CLUSTER_y)"
print(df.query(con))

  PROJECT CLUSTER_x MARKET_x CLUSTER_y MARKET_y Exist
0     P17         A    CHINA         C    CHINA  both
3     P18         P    INDIA         P    JAPAN  both

请记住,如果列名包含空格或特殊字符,则无法生成正确的结果。你知道吗

相关问题 更多 >