将不同列中的值合并为python列表中的一个

时间:2016-02-12 23:13:34

标签: python list pandas merge

我有一个如下所示的列表。

Gamecode    rush    pass
23....89     347    
23....89             650
23....90     654    
23....90             230

代码如下。

temp = {}
for row in combineddff.itertuples():
    temp={}
    if row[1] in ('RUSH', 'PASS'):
        temp['GameCode'] =  row[0]
        if row[1] == 'RUSH':
            temp['rush'] = row[10]
        else:
             temp['pass'] = row[10]

    else:
        continue
    templist.append(temp)

print templist
my_df = pd.DataFrame(templist)
my_df.to_csv('data/results_yards.csv', index=False, header=False)

我想将templist中单独行的rush和pass值组合成一行,其中“GameCode”,“Rush”和“Pass”为值。请帮助。

2 个答案:

答案 0 :(得分:1)

尝试使用pd.merge方法:

import pandas as pd

rush = pd.DataFrame({'Gamecode': [2389, 2390], 'rush': [347, 654]})
pss = pd.DataFrame({'Gamecode': [2389, 2390], 'pass': [650, 230]})

print(pd.merge(rush, pss, on='Gamecode'))

输出:

   Gamecode  rush  pass
0      2389   347   650
1      2390   654   230

答案 1 :(得分:1)

如果没有价值,我假设您的列为“无”。

game_code = 'GameCode'
pass_yds = 'PASS'
rush_yds = 'RUSH'

output_list = []
for row in combineddff.itertuples():
    if row[0] == game_code:
        if row[2] is not None: pass_yds = row[2]
        if row[1] is not None: rush_yds = row[1]
    else:
        output = (game_code, pass_yds, rush_yds)
        output_list.append(output)

# Flush the last group
output = (game_code, pass_yds, rush_yds)
output_list.append(output)

编辑:评论后

templist = [
    { 'GameCode': 'A', 'PASS': '1' },
    { 'GameCode': 'A', 'RUN': '2' },
    { 'GameCode': 'B', 'PASS': '3' },
    { 'GameCode': 'B', 'RUN': '4' },
]

merged = None
output_list = []

for t in templist:
    if merged is None:
        merged = t
    elif merged['GameCode'] == t['GameCode']:
        merged.update(t)
    else:
        output_list.append(merged)
        merged = t