【发布时间】:2017-07-18 02:04:01
【问题描述】:
我有一个格式的 CSV
Team, Player
我想做的是对现场团队应用过滤器,然后从每个团队中随机抽取 3 名球员。
例如,我的 CSV 看起来像:
Man Utd, Ryan Giggs
Man Utd, Paul Scholes
Man Utd, Paul Ince
Man Utd, Danny Pugh
Liverpool, Steven Gerrard
Liverpool, Kenny Dalglish
...
我希望最终得到一个由每支球队的 3 名随机球员组成的 XLS,并且在少于 3 名的情况下只有 1 或 2 名,例如,
Man Utd, Paul Scholes
Man Utd, Paul Ince
Man Utd, Danny Pugh
Liverpool, Steven Gerrard
Liverpool, Kenny Dalglish
我开始使用 XLRD,我的原始帖子是 here。
我现在正在尝试使用 Pandas,因为我相信这在未来会更加灵活。
所以,在伪代码中我想做的是:
foreach(team in csv)
print random 3 players + team they are assigned to
我一直在浏览 Pandas 并试图找到执行此操作的最佳方法,但找不到与我想做的类似的事情(这对 Google 来说是一件困难的事情!)。到目前为止,这是我的尝试:
import pandas as pd
from collections import defaultdict
import csv as csv
columns = defaultdict(list) # each value in each column is appended to a list
with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
reader = csv.DictReader(f) # read rows into a dictionary format
for row in reader: # read a row as {column1: value1, column2: value2,...}
print(row)
#for (k,v) in row.items(): # go over each column name and value
# columns[k].append(v) # append the value into the appropriate list
# based on column name k
所以我已经注释掉了最后两行,因为我不确定是否需要我。我现在每行都被打印出来,所以我只需要为每个足球队随机选择 3 行(或者在较少的情况下选择 1 或 2 行)。
我怎样才能做到这一点?有什么提示/技巧吗?
谢谢。
【问题讨论】:
标签: python python-3.x csv pandas random