Reputation: 35
I have a list like the one below.
Gamecode rush pass
23....89 347
23....89 650
23....90 654
23....90 230
the code is below.
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)
I want to combine the rush and pass values of separate rows in the templist into one row with "GameCode", "Rush" and "Pass" as values. kindly help.
Upvotes: 2
Views: 301
Reputation: 15300
I'm assuming your columns are 'None' if there is no value.
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)
Edit: after comments
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
Upvotes: 1
Reputation: 210832
try to use pd.merge method:
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'))
Output:
Gamecode rush pass
0 2389 347 650
1 2390 654 230
Upvotes: 1