pandas如何创建简单的交叉表而不进行聚合?

Dro*_*man 2 python crosstab aggregate-functions pandas

我有一个包含 3 列的 pandas 表:parent_male、parent_female、offsprings - 所有字符串。我想创建一个简单的稀疏交叉表,将男性与女性以及后代作为值 - 我如何编写一个 aggfunc 来执行此操作。(不需要真正的聚合) - 只需在空格中放置一个空字符串。

jez*_*ael 6

IIUC 你需要pivot

df = df.pivot(index='parent_male', columns='parent_female', values='offsprings')
Run Code Online (Sandbox Code Playgroud)

如果出现错误:

ValueError:索引包含重复条目,无法重塑

使用pivot_table

所以最终的解决方案是:

ct = pd.pivot_table(d['male'], d['female'], d['offsprings'], aggfunc=','.join)
Run Code Online (Sandbox Code Playgroud)