Skip to main content
 首页 » 编程设计

python之获取一长串项目并 reshape 为数据框 "rows"- pandas python 3

2024年10月01日7dyllove98

我有一长串要按设定时间间隔放入数据框中的项目。我有另一个带有“列名”的列表。

例如

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

我想创建一个如下所示的数据框:

    |   Title   |   Date   |   Abstract   |   ID   |   Volume    
__________________________________________________________________ 
 
0         a          b            c           d          e 
1         f          g            h           i          j 
2         k          l            m           n          o 

感谢您的任何建议!

请您参考如下方法:

您需要带有 numpy.reshape 的 DataFrame 构造函数:

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 :

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