Skip to main content
 首页 » 编程设计

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

2024年10月24日9zhujiabin

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

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) 

我想将模板列表中不同行的 rush 和 pass 值合并为一行,并将“GameCode”、“Rush”和“Pass”作为值。请帮忙。

请您参考如下方法:

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

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