取得一长串物品,并将其整形为数据框“行",以调整行数.- pandas 蟒蛇3 [英] Take long list of items and reshape into dataframe "rows" - pandas python 3

查看:39
本文介绍了取得一长串物品,并将其整形为数据框“行",以调整行数.- pandas 蟒蛇3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一长串要按设定间隔放入数据框中的项目.我还有另一个带有列名"的列表.

I have a long list of items that I want to put in a data frame at set intervals. I have another list with "column names".

例如

colnames = ['Title', 'Date', 'Abstract', 'ID', 'Volume']
data = [a, b, c, d, e, f, g, h, i ,j, k, l, m, n, o]

我想创建一个看起来像这样的数据框:

I want to create a data frame that looks like:

    |   Title   |   Date   |   Abstract   |   ID   |   Volume   
__________________________________________________________________

0         a          b            c           d          e
1         f          g            h           i          j
2         k          l            m           n          o

谢谢您的建议!

推荐答案

您需要 DataFrame 构造函数和

You need DataFrame constructor with numpy.reshape:

import pandas as pd
import numpy as np

colnames = ['Title', 'Date', 'Abstract', 'ID', 'Volume']
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ,'j', 'k', 'l', 'm', 'n', 'o']

df = pd.DataFrame(np.array(data).reshape(-1, len(colnames)), columns=colnames)
print (df)
  Title Date Abstract ID Volume
0     a    b        c  d      e
1     f    g        h  i      j
2     k    l        m  n      o

但是如果某些值可能丢失,请使用 unstack :

But if some values are missing is possible use unstack:

colnames = ['Title', 'Date', 'Abstract', 'ID', 'Volume']
data = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ,'j', 'k', 'l', 'm']

df = pd.DataFrame(data, columns=['col'])
df.index = [df.index // len(colnames), df.index % len(colnames)]
df = df['col'].unstack()
df.columns = colnames
print (df)
  Title Date Abstract    ID Volume
0     a    b        c     d      e
1     f    g        h     i      j
2     k    l        m  None   None

这篇关于取得一长串物品,并将其整形为数据框“行",以调整行数.- pandas 蟒蛇3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆