【问题标题】:How do I count in a Pandas DataFrame?如何计算 Pandas DataFrame?
【发布时间】:2021-08-05 14:48:26
【问题描述】:
import pandas as pd

# Read CSV data file:
df = pd.read_csv('~/nclab-data-read/titanic.csv')

# Port where most passengers embarked:
port = df['Embarked'].mode()[0]
**# Count these passengers:
n_port = df[['Name']].loc[df['Embarked'] == 1].count()[0]**

我相信我在最下面一行有一些不正确的地方,但不知道是什么。

【问题讨论】:

  • sum(df['Embarked'] == port) 可能足以满足您的需求。
  • 为了改进这个问题和未来的问题,请将您的数据的一小部分作为可用于测试以及预期输出的可复制代码片段。请参阅 MRE - Minimal, Reproducible, ExampleHow to make good reproducible pandas examples
  • 天啊,这么简单。非常感谢!
  • Series.value_counts 在这里效果很好,df['embarked'].value_counts().head(1)

标签: python pandas dataframe count mode


【解决方案1】:

count() 返回非空值的数量。如果应用于 DataFrame,它会返回一个数组,每列有 1 个值(因此您需要取索引 0)。

应用于系列时,您会直接获得编号。

n_port = df.loc[df['Embarked'] == 1, 'Name'].count()

显然,这两行将返回相同的结果。

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 2017-12-15
    • 2019-08-01
    • 2018-10-12
    • 2019-07-17
    • 2014-12-03
    • 2021-04-16
    相关资源
    最近更新 更多