-
开心每一天1111
这是使用pivot_table. 要记住一些棘手的事情:您需要将两者都指定'PRIO', 'Art'为数据透视索引我们还可以使用两个聚合函数在一次调用中完成我们必须重命名 0 级列以区分它们。所以你需要交换级别并重命名out = df.pivot_table(index=['PRIO', 'Art'], columns='Name', values='Value', aggfunc=[lambda x: 1, 'first'])# get the column names rightd = {'<lambda>':'is_present', 'first':'value'}out = out.rename(columns=d, level=0)out.columns = out.swaplevel(1,0, axis=1).columns.map('_'.join)print(out.reset_index()) PRIO Art Alpha_is_present Beta_is_present Theta_is_present Alpha_value \0 1 A 1.0 1.0 NaN 0.0 1 2 A 1.0 NaN NaN 3.0 2 2 B NaN NaN 1.0 NaN Beta_value Theta_value 0 1.0 NaN 1 NaN NaN 2 NaN 2.0
-
千万里不及你
pd.crosstab()这是和的示例groupby()。df = pd.concat([pd.crosstab([df['PRIO'],df['Art']], df['Name']),df.groupby(['PRIO','Art','Name'])['Value'].sum().unstack().add_suffix('_value')],axis=1).reset_index()df| | Alpha | Beta | Theta | Alpha_value | Beta_value | Theta_value ||:---------|--------:|-------:|--------:|--------------:|-------------:|--------------:|| (1, 'A') | 1 | 1 | 0 | 0 | 1 | nan || (2, 'A') | 1 | 0 | 0 | 3 | nan | nan || (2, 'B') | 0 | 0 | 1 | nan | nan | 2 |
-
元芳怎么了
Groupby 两次,首先以 Name 和 suffix 为中心值。Next groupby 相同的命令并找到唯一的值。加入两者。在加入中,删除重复的列并根据需要重命名其他列g=df.groupby([ 'Art','PRIO', 'Name'])['Value'].\first().unstack().reset_index().add_suffix('_value')print(g.join(df.groupby(['PRIO', 'Art','Name'])['Value'].\ nunique().unstack('Name').reset_index()).drop(columns=['PRIO_value','Art'])\ .rename(columns={'Art_value':'Art'})) Name Art Alpha_value Beta_value Theta_value PRIO Alpha Beta Theta0 A 0.0 1.0 NaN 1 1.0 1.0 NaN1 A 3.0 NaN NaN 2 1.0 NaN NaN2 B NaN NaN 2.0 2 NaN NaN 1.0