【问题标题】:Python Pandas Using dataframe.stack().value_counts() -- How to get values of counted objects?Python Pandas 使用 dataframe.stack().value_counts() - 如何获取计数对象的值?
【发布时间】:2017-03-09 00:22:02
【问题描述】:

我有一个数据框,其中每一行代表一周中的某一天,每一列代表当天与服务器通信失败的联网设备的序列号。

我正在尝试获取一整周未能通信的一系列序列号。

代码块:

counts = df.stack().value_counts()
seven_day = counts[counts == 7]
for a in seven_day:
    print(a)

问题是没有打印任何内容。我想要的是序列号列表,而不是计数本身。

这个问题是来自: Python Pandas -- Determine if Values in Column 0 Are Repeated in Each Subsequent Column

【问题讨论】:

  • 你想遍历索引seven_day = counts[counts == 7] for a in seven_day.index: print(a)

标签: python loops pandas indexing series


【解决方案1】:

value_counts 返回一个 Series,其中值作为索引,计数作为值,所以你想遍历索引:

counts = df.stack().value_counts()
seven_day = counts[counts == 7]
for a in seven_day.index:
    print(a)

应该工作

【讨论】:

  • 就是这样。感谢@EdChum 在这两个问题上帮助我。
【解决方案2】:

另一种解决方案是使用Series.iteritems:

counts = df.stack().value_counts()
seven_day = counts[counts == 7]

for index, val in seven_day.iteritems():
    print(index)

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2021-12-13
    • 2022-12-05
    • 1970-01-01
    • 2016-06-02
    • 2018-06-23
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多