【问题标题】:Iterate through groups of rows which have a unique col value in Pandas遍历在 Pandas 中具有唯一列值的行组
【发布时间】:2021-10-30 19:19:29
【问题描述】:

以这段代码为例:

for col in df:
    print(df[col].unique())

它将打印col 下的每个唯一字符串/值,而不是 df 中的每一行。这是我想要的,但不是真的。

我想要做的是迭代地获取与第一个唯一 col 值关联的所有行,在它们上执行一些代码,然后转到第二个唯一 col 值并执行相同的操作,直到我已经用尽了每批唯一值。我怎样才能做到这一点?我想传达我想要的最简单的方法是想象你可以做什么:

for col.unique() in df:
        #do some processing here

【问题讨论】:

    标签: python pandas for-loop


    【解决方案1】:

    你的意思是:

    for col in df:
        for x in df[col].unique():
            print(df.loc[df[col].eq(x), col])
    

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多