在Python中重新安排元组列表

时间:2015-11-16 03:41:19

标签: python list

在这里,我有一个元组列表,格式如下:

mylist = [('t1', 0, 23),
          ('t1', 1, 24),
          ('t1', 2, 25),
          ('t2', 0, 22),
          ('t2', 1, 25),
          ('t2', 2, 26)]

现在,我想以某种方式安排列表,以便将其保存为CSV文件,如下图所示:

  t1 t2
0 23 22
1 24 25
2 25 26

我该怎么办?

3 个答案:

答案 0 :(得分:2)

熊猫是最好的方式。

如果您无法使用Pandas,则可以使用cvs module

mylist = [('t1', 0, 23),
('t1', 1, 24),
('t1', 2, 25),
('t2', 0, 22),
('t2', 1, 25),
('t2', 2, 26)]

import csv

di={}
for t in mylist:
    di.setdefault(t[0], []).append(t[2])

with open(fn, 'w') as cf:
    w=csv.writer(cf)
    w.writerow(['index']+di.keys())
    line=0
    for t in zip(*di.values()):
        w.writerow([line]+list(t))
        line+=1      
然后

文件:

index,t2,t1
0,22,23
1,25,24
2,26,25

如果t1, t2列表中的订单相关,请使用OrderedDict代替dict。

答案 1 :(得分:1)

我很懒,所以我使用pandas

import pandas as pd

mylist = [('t1', 0, 23),
          ('t1', 1, 24),
          ('t1', 2, 25),
          ('t2', 0, 22),
          ('t2', 1, 25),
          ('t2', 2, 26)]


df = pd.DataFrame(columns=['t1','t2'], index=[0,1,2])

print df
#    t1   t2
#0  NaN  NaN
#1  NaN  NaN
#2  NaN  NaN

for col, row, val in mylist:
    df[col][row] = val

print df
#   t1  t2
#0  23  22
#1  24  25
#2  25  26

#df.to_csv('filename.csv') # comma separated values
df.to_csv('filename.csv', sep=' ')

编辑:

import pandas as pd

mylist = [('t1', 0, 23),
          ('t1', 1, 24),
          ('t1', 2, 25),
          ('t2', 0, 22),
          ('t2', 1, 25),
          ('t2', 2, 26)]


df = pd.DataFrame()

for col, row, val in mylist:
    if col not in df.columns:
        #df[col] = pd.Series() # new column with NaN
        df[col] = 0 # new column with zeros

    if row not in df.index:
        #df.loc[row] = pd.Series() # new row with NaN
        df.loc[row] = 0 # new row with zeros

    df[col][row] = val

print df
#   t1  t2
#0  23  22
#1  24  25
#2  25  26

df.to_csv('filename.csv', sep=' ')

答案 2 :(得分:1)

这是一个不使用loc的解决方案:

import pandas as pd

mylist = [('t1', 0, 23),
          ('t1', 1, 24),
          ('t1', 2, 25),
          ('t2', 0, 22),
          ('t2', 1, 25),
          ('t2', 2, 26)]
firstkey = mylist[0][0]
mydict = {}
indices = []
for key, index, val in mylist:
    try:
        mydict[key].append(val)
    except KeyError:
        mydict[key] = [val]
    if key == firstkey:
        indices.append(index)
df = pd.DataFrame(mydict)
df.index = indices
df.to_csv('filename.csv')