如何根据条件从数据框中交叉列?

How to crosstab columns from dataframe based on a condition?

我经常需要交叉 table 来对我的数据进行预分析。我可以用 pd.crosstab(df['column'], df['column']) 生成一个基本的交叉 table 但无法添加一个条件(逻辑表达式),以仅将此交叉 table 过滤到我的数据框的一个子集。

我试过 pd.crosstab(df['health'], df['money']) if df['year']==1988 和 if 的几个位置。我希望它很容易解决,但我对 Python 和 Pandas 比较陌生。

import pandas as pd
df = pd.DataFrame({'year': ['1988', '1988', '1988', '1988', '1989', '1989', '1989', '1989'],
                   'health': ['2', '2', '3', '1', '3', '5', '2', '1'],
                   'money': ['5', '7', '8', '8', '3', '3', '7', '8']}).astype(int)

# cross table for 1988 and 1999
pd.crosstab(df['health'], df['money'])

crosstab 之前按 boolean indexing 过滤:

df1 = df[df['year']==1988]
df2 = pd.crosstab(df1['health'], df1['money'])

编辑:您可以分别过滤每一列:

mask = df['year']==1988
df2 = pd.crosstab(df.loc[mask, 'health'], df.loc[mask, 'money'])