gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:44 25 4
gpt4 key购买 nike

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

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

关于python - 将不同列中的值合并为python列表中的一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com