如何将此列表转换为 3xN 矩阵? Python
Posted
技术标签:
【中文标题】如何将此列表转换为 3xN 矩阵? Python【英文标题】:How to transfer this list to a 3xN matrix? Python 【发布时间】:2020-01-03 19:23:46 【问题描述】:my_list = ["TITLE","COMPANY","TENURE",
"Board Member","Softbank Corp","06/2007–06/2015",
"Chairman","Alibaba.Com Ltd","10/2007–PRESENT",
"Board Member","Huayi Brothers","FORMER"]
我有上面的列表,我想将其转换为 3xN 格式(3 列,N 行)
预期输出:
TITLE COMPANY TENURE
Board Member Softbank Corp 06/2007–06/2015
Chairman Alibaba.Com Ltd 10/2007–PRESENT
Board Member Huayi Brothers FORMER
提前感谢您的帮助!
【问题讨论】:
你试过用熊猫吗? pandas.pydata.org 【参考方案1】:你可以使用 pandas 数据框:
可以使用单个列表或列表列表创建 DataFrame。
import pandas as pd
my_list = ["TITLE","COMPANY","TENURE",
"Board Member","Softbank Corp","06/2007–06/2015",
"Chairman","Alibaba.Com Ltd","10/2007–PRESENT",
"Board Member","Huayi Brothers","FORMER"]
# Convert flat list into nested list with 3 items
data_ = [my_list[i:i + 3] for i in range(0,len(my_list),3)]
#Create a DataFrame from Lists
print (pd.DataFrame(data_[1:],columns=data_[0:1][0]))
输出:
TITLE COMPANY TENURE
0 Board Member Softbank Corp 06/2007–06/2015
1 Chairman Alibaba.Com Ltd 10/2007–PRESENT
2 Board Member Huayi Brothers FORMER
【讨论】:
以上是关于如何将此列表转换为 3xN 矩阵? Python的主要内容,如果未能解决你的问题,请参考以下文章