从CSV加载的随机样本与熊猫

问题描述:

我有格式的CSV从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到结束,只有在那里是小于的情况下1或2 3例如,

Man Utd, Paul Scholes 
Man Utd, Paul Ince 
Man Utd, Danny Pugh 
Liverpool, Steven Gerrard 
Liverpool, Kenny Dalglish 

我开始使用XLRD,我的原始帖子是here

我现在正在尝试使用熊猫,因为我相信这将会更灵活地应对未来。

因此,在伪代码是我想要做的是:

foreach(team in csv) 
    print random 3 players + team they are assigned to 

我一直在寻找通过熊猫,并试图找到这样做的最佳方法,但我找不到类似的东西是什么我想要这样做(这对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)。

我该如何做到这一点?任何提示/技巧?

谢谢。

首先使用更加优化read_csv

import pandas as pd 

df = pd.read_csv('DataFrame') 

现在,作为一个随便举个例子,使用lambda通过随机数据框获得一个随机子集(替换“X”与LivFC为例):

In [] 
df= pd.DataFrame() 
df['x'] = np.arange(0, 10, 1) 
df['y'] = np.arange(0, 10, 1) 
df['x'] = df['x'].astype(str) 
df['y'] = df['y'].astype(str) 

df['x'].ix[np.random.random_integers(0, len(df), 10)][:3] 

Out [382]: 
0 0 
3 3 
7 7 
Name: x, dtype: object 

这会让你更熟悉的大熊猫,但与0.16.x版本开始,现在有一个DataFrame.sample法内置:

df = pandas.DataFrame(data) 

# Randomly sample 70% of your dataframe 
df_0.7 = df.sample(frac=0.7) 

# Randomly sample 7 elements from your dataframe 
df_7 = df.sample(n=7) 
For either approach above, you can get the rest of the rows by doing: 

df_rest = df.loc[~df.index.isin(df_0.7.index)] 
+0

感谢您的回应,非常有教育意义。似乎这两种解决方案都需要从数据框中获得70%的数据 - 而不确保每个团队都在输出数据集中表示。我想确保每队返回3名球员。有没有办法做到这一点 ? –

+0

确保通过在df ['This']中执行子查询,这将会非常高效,因为DataFrames会为这些任务实现布尔值掩码。这样你可以构建一个具有你想要的功能的DataFrame。也考虑接受它是否回答了你的问题。 – SerialDev