问题描述
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]**
我相信我在底行有一些不正确的东西,但不知道是什么。
解决方法
count() 返回非空值的数量。如果应用于 DataFrame,它将返回一个每列 1 个值的数组(因此您需要采用索引 0)。
应用于系列时,您会直接获得编号。
n_port = df.loc[df['Embarked'] == 1,'Name'].count()
显然,两行都将返回相同的结果。