我该怎么做才能在python中制作长到宽的格式

时间:2018-04-07 08:01:00

标签: python pandas

我有这么长的数据。我喜欢按每个30分类并单独保存。 像这样的数据打印,     main2.py 这是一个相当简单的问题,但我需要你的帮助.. 谢谢。 (如何从打印的一个结果中列出一个列表?列表添加?

2 个答案:

答案 0 :(得分:2)

我认为需要按照模数和底线除以repartition创建MultiIndex除以DataFrame的长度然后unstack

但如果长度模数不等于np.arange(例如0),则最后一个值与最后一列不匹配,并添加了(30 % 12)

None

<强>设置

N = 12
r = np.arange(len(df))
df.index = [r % N, r // N]
df = df['col'].unstack()
print (df)
          0        1        2
0   A292340  A236350  A196030
1   A291630  A233740  A196220
2   A278240  A233160  A167860
3   A267770  A225800  A152500
4   A267490  A225060  A123320
5   A261250  A225050  A122630
6   A261110  A225040     None
7   A253150  A225130     None
8   A252400  A219900     None
9   A253250  A204450     None
10  A243890  A204480     None
11  A243880  A204420     None

答案 1 :(得分:2)

如果你没有Pandas和Numpy模块,你可以使用它:

设定:

long_list = ['A292340', 'A291630', 'A278240', 'A267770', 'A267490', 'A261250', 'A261110', 'A253150', 'A252400',
             'A253250', 'A243890', 'A243880', 'A236350', 'A233740', 'A233160', 'A225800', 'A225060', 'A225050',
             'A225040', 'A225130', 'A219900', 'A204450', 'A204480', 'A204420', 'A196030', 'A196220', 'A167860',
             'A152500', 'A123320', 'A122630', 'A292340', 'A291630', 'A278240', 'A267770', 'A267490', 'A261250',
             'A261110', 'A253150', 'A252400', 'A253250', 'A243890', 'A243880', 'A236350', 'A233740', 'A233160',
             'A225800', 'A225060', 'A225050', 'A225040', 'A225130', 'A219900', 'A204450', 'A204480', 'A204420',
             'A196030', 'A196220', 'A167860', 'A152500', 'A123320', 'A122630']

代码:

number_elements_in_sublist = 30

sublists = []
sublists.append([])
sublist_index = 0
for index, element in enumerate(long_list):
    sublists[sublist_index].append(element)
    if index > 0:
        if (index+1) % number_elements_in_sublist == 0:
            if index == len(long_list)-1:
                break
            sublists.append([])
            sublist_index += 1

for index, sublist in enumerate(sublists):
    print("Sublist Nr." + str(index+1))
    for element in sublist:
        print(element)