Python 导出到 CSV

标签 python export-to-csv

这是我正在使用的数据(示例):

('Bouwmeester', [(0, 37), (155, 194), (327, 420), (541, 602), (654, 717), (761, 834), (1001, 1052), (0, 27), (79, 119), (405, 460), (546, 624), (750, 798), (834, 897), (1061, 1139), (0, 33), (170, 204), (289, 328), (447, 498), (575, 576), (729, 766), (962, 995), (1073, 1113), (1163, 1200)])
('Schwartz', [(0, 40), (165, 209), (362, 417), (550, 567), (761, 809), (881, 954), (1052, 1113), (27, 54), (195, 295), (482, 546), (707, 757), (906, 1003), (1080, 1126), (0, 33), (145, 229), (353, 408), (492, 561), (576, 640), (736, 766), (820, 870), (1094, 1163)])
('Foligno', [(0, 40), (176, 209), (362, 416), (552, 567), (761, 835), (883, 954), (459, 502), (546, 583), (757, 826), (1189, 1200), (0, 33), (212, 249), (353, 413), (575, 576), (696, 722), (722, 762)])

这是我到目前为止的脚本:

import csv
from itertools import combinations, product

#Header = LastName  StartTime  EndTime  Duration Period TeamAbbrev Position

#Import Game
with open('2017020397.csv', newline='') as f:
    next(f)
    skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
    data = skaters.splitlines()

def to_secs(ms):
    ''' Convert a mm:ss string to seconds '''
    m, s = map(int, ms.split(':'))
    return 60 * m + s

# Store a list of (start, end) times for each player
players = {}
for row in data:
    name, start, end = row.split(None, 3)[:3]
    times = to_secs(start), to_secs(end)
    players.setdefault(name, []).append(times)

for t in players.items():
    print(t)

outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Shift1"])
writer.writerow([name, times])
outfile.close()

输出:

Player  Shift1
Dumba   (39, 39)

输出是最后一个数据而不是整个文件。另外,我希望所有的转换都在自己的单元格中进行输出示例:

Player        Shift1       Shift2      Shift3       Shift4
Bouwmeester   (0, 37)    (155, 194)  (327, 420)   (541, 602)

最佳答案

主要问题是您只在标题后写入一行:

writer.writerow([name, times])

相反,您需要写入数据的每一行,您可以在第二个 for 循环中执行此操作。

您还需要通过查找玩家时间列表的最大长度来计算有多少 Shift# 列。这可以简单地通过使用循环或内置 max 函数来完成:

# the loop way
shift_count = 0
for times in players.values():
    if len(times) > shift_count:
        shift_count = len(times)

# the quicker built-in way
shift_count = max(
    len(shift_times) for shift_times in players.values()
)

# then make the column names
shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

将这两个放在一起:

# Move the file prep above the loop
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)

shift_count = max(
    len(shift_times) for shift_times in players.values()
)

shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

writer.writerow(["Player"] + shift_cols)

for t in players.items():
    print(t)

    row = [
        t[0],  # the first column is the player's name
    ]
    row += t[1]  # then all of the shift times next to it

    writer.writerow(row)

outfile.close()

关于Python 导出到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47725845/

相关文章:

utf-8 - 将工作表导出为 UTF-8 CSV 文件(使用 Excel-VBA)

c# - 将 double 值导出到 CSV

Python:如何在未处理的异常后控制命名空间?

python - Flask加载本地json

python - 在 'df.size()' 函数后操作新列?

python - 如何获取数据集中某些单词的值计数

mysql - magento 订单导出时出现相同 ID 错误

Powershell - 将 .txt 数据输出到 CSV

powershell - 我可以在 Powershell 中将标题行添加到 CSV 导出吗?

python - 在不使用 `key` 参数的情况下对自定义类进行排序?