使用行创建不同的列

问题描述 投票:0回答:1

我有这个输入

在此输入图片描述

我需要得到这个输出

在此输入图片描述

我正在使用 pandas 库和 python,我不知道是否可行。预先感谢您提供任何想法或示例

pivot_table(values=['描述','票号'], index='分区', columns=['描述','票号'], aggfunc='count') Report_new.reset_index(inplace=True)

python pandas dataframe indexing pivot-table
1个回答
0
投票

您可以按所需的列进行分组,将值转换为列表并创建一个新的 DataFrame。

假设这个示例 DataFrame

   a    b      c
0  6  foo  hello
1  9  bar  hello
2  6  foo  world
3  1  foo  world
4  1  bar  world
5  2  foo  world
6  8  foo  world
7  7  foo  hello
8  3  bar  hello
9  5  foo  hello

您可以尝试以下方法

import pandas as pd
import numpy as np

# random data
np.random.seed(1)
df = pd.DataFrame(np.transpose([np.random.randint(1,10, 10),
                  np.random.choice(['foo', 'bar'], 10),
                  np.random.choice(['hello', 'world'], 10)]), columns=list('abc'))

# groupby and convert values to list
grp = df.groupby(['b', 'c'])['a'].agg(list)
# create a new data frame
# you can reset the index if you want
new_df = pd.DataFrame(grp.tolist(), index=grp.index)



           0     1     2     3
b   c                         
bar hello  9     3  None  None
    world  1  None  None  None
foo hello  6     7     5  None
    world  6     1     2     8
© www.soinside.com 2019 - 2024. All rights reserved.