【问题标题】:Efficient selection of rows in Pandas dataframe based on multiple conditions across columns基于跨列的多个条件有效选择 Pandas 数据框中的行
【发布时间】:2020-05-18 11:16:03
【问题描述】:

我正在尝试根据条件创建一个新的 pandas 数据框。这是原始数据框:

        topic1 topic2 
name1    1      4
name2    4      4
name3    4      3
name4    4      4
name5    2      4

我想选择任意行,以便 topic1 == 4 在新数据框中出现 2 次,topic2 == 4 出现 3 次。一旦完成,我想停止代码。

bucket1_topic1 = 2
bucket1_topic2 = 3

我写了这个非常复杂的启动器,它“几乎”可以工作......但是我在处理同时满足 topic1 和 topic2 条件的行时遇到了问题。有什么更有效和正确的方法来做到这一点?

rows_list = []

counter1 = 0
counter2 = 0

for index,row in data.iterrows():
    if counter1 < bucket1_topic1:
        if row.topic1 == 4:
            counter1 +=1
            rows_list.append([row[1], row.topic1, row.topic2])

    if counter2 < bucket1_topic2:
        if row.topic2 == 4 and row.topic1 !=4:
            counter2 +=1
            if [row[1], row.topic1, row.topic2] not in rows_list:
                rows_list.append([row[1], row.topic1, row.topic2])

想要的结果,topic1 == 4 出现两次,topic2 == 4 出现 3 次:

        topic1 topic2 
name1    1      4
name2    4      4
name3    4      3
name5    2      4

【问题讨论】:

  • 您能否更清楚地描述一下条件,如果它们满足我的条件为 4桶有点混乱
  • 做了一些更新,希望现在更清楚了!

标签: python pandas loops if-statement conditional-statements


【解决方案1】:

避免循环并考虑使用DataFrame.sample 任意重新洗牌(其中frac=1 表示返回数据帧的100% 部分),然后使用groupby().cumcount() 计算运行组计数。最后,使用逻辑子集进行过滤:

df = (df.sample(frac=1)
        .assign(t1_grp = lambda x: x.groupby(["topic1"]).cumcount(),
                t2_grp = lambda x: x.groupby(["topic2"]).cumcount())
     )

final_df = df[(df["topic1"].isin([1,2,3])) | 
              (df["topic2"].isin([1,2,3])) |
              ((df["topic1"] == 4) & (df["t1_grp"] < 2)) |
              ((df["topic2"] == 4) & (df["t2_grp"] < 3))]

final_df = final_df.drop(columns=["t1_grp", "t2_grp"])

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 2022-01-26
    • 1970-01-01
    • 2022-10-13
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2017-01-21
    相关资源
    最近更新 更多