相关文章推荐
大力的山羊  ·  引用 | 微信开放文档·  4 月前    · 
谦和的手术刀  ·  转移键值对SQL表·  1 年前    · 
宽容的水桶  ·  eclipse - Read csv ...·  1 年前    · 
df = {'index': [27, 28, 29, 30, 31],
'data': [[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28],
[29, 30, 31, 32, 33, 34, 35]]}

我想把'data'键改成等效的转置矩阵,我想把'index'键重复的次数与结果'data'键中的列数一样多(本例中为5次)。

df = {'index': [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31],
'data': [[1, 8, 15, 22, 29],
[2, 9, 16, 23, 30],
[3, 10, 17, 24, 31],
[4, 11, 18, 25, 32],
[5, 12, 19, 26, 33],
[6, 13, 20, 27, 34],
[7, 14, 21, 28, 35]]}

我怎样才能继续?谢谢。

2 个评论
数据框架包含列表?你介意分享生成数据框架的代码吗?
不,这只是一个例子,而不是一个生成的数据框架。
python
pandas
dictionary
Rinnosuke
Rinnosuke
发布于 2021-09-21
3 个回答
cards
cards
发布于 2021-09-21
已采纳
0 人赞同

你可以用zip进行转置。

df = {'index': [27, 28, 29, 30, 31],
'data': [[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28],
[29, 30, 31, 32, 33, 34, 35]]}
df_new = {}
df_new['index'] = [df['index']]* len(df['data'])
df_new['data'] = list(zip(*df['data']))
print(df_new)
    
BENY
BENY
发布于 2021-09-21
0 人赞同

Try from_records

out = pd.DataFrame.from_records(data=df['data'],index=df['index'])
Out[191]: 
     0   1   2   3   4   5   6
27   1   2   3   4   5   6   7
28   8   9  10  11  12  13  14
29  15  16  17  18  19  20  21
30  22  23  24  25  26  27  28
31  29  30  31  32  33  34  35