2017-05-08 54 views
0

我非常喜歡Python的新手,但學習。我在工作中一直負責獲取數據的CSV(2500行)以下面的格式(如我們無法弄清楚如何做到這一點在Excel中):Python - CSV - 每行數字到元組的所有排列

RefNumber  Reviewer 1 Reviewer 2 Reviewer 3 Reviewer 4 Reviewer 5 
    9676/2   6   3   2 
    0526/4   6   3   1   5   1 
    1842/1   5   3   1   5 
    2693/3   5   5   1   2 
    2515/1   6   3   1   5   3 
    2987/1   4   1   3 
    3841/1   4   3   1 
    3402/1   4   3   1   5 

併產生一個CSV所有的每個平均您可以從每行獲得的數字排列(最少3個)。

1分之3841上面將產生的{4,3,1}的元組,和平均2.7

一分之三千四百零二上述將產生的{4元組,3,1},{4,3,1,5},{3,1,5},{4,1,5}等,平均值爲2.7,3.3,3,3.3等。

我試圖想出這樣做的最好方法,因爲我還需要知道每個平均值,它包含的元組中有多少個數字,即{4,3,1}會產生一個平均值o ˚F2.7和元組的編號的個數爲3

基本上是我想做的產生是這樣的:

RefNumber  Avg 1  Avg 2  Avg 3  Avg 4 Avg 5 
    3841/1  2.7   
    3402/1  2.7  3.3   3   3.5 

但我想展現的元組數字的數,我可以運行它是9次(最多有12次評論),並且每個數據表都在其自己的選項卡上。

我在技術上也需要每個元組的標準偏差和分數的範圍,但這已經超過我的專業知識wayyyyy,所以我想我可以放棄或以某種方式手動執行。

任何想法從哪裏開始呢?

+0

我想'subset'比'permuatation'更合適。排列組的平均值是不變的。 – handle

+0

從閱讀數據開始,例如與https://docs.python.org/3/library/csv.html – handle

+0

子集將工作?我認爲一個子集只會產生一組所有的數字,即如果該行包含8個數字,它將是8個數字的一​​個子集,而我希望所有3和8之間的組合? – ScoutEU

回答

3

您可以使用csv模塊讀取csv並提取數據和itertools模塊以獲取所有組合。看看它是否在做這項工作。此外,我仍然保留了平均值,但是我發現您只是使用1個小數點,您可以通過舍入結果輕鬆獲得。猜猜你現在可以保存結果。

from itertools import combinations as cb 
import csv 
with open("test.csv") as f: 
    reader=csv.reader(f) 
    next(reader, None) # skip header 
    data=[filter(None,i) for i in reader] 

def avgg(x): 
    ll=[float(i) for i in x[1:]] #take review no and convert to float 
    n=len(ll) 
    avg_list=[x[0]] #start result list with ref no. 
    for i in range(3,n+1): 
     for j in cb(ll,i): 
      # print(j) #see the combination 
      avg_list.append(sum(j)/i) 
    return avg_list 

for x in data: 
    print(avgg(x)) 
+0

非常感謝你,這非常完美!我需要考慮一種方法來知道哪些數字適用於元組中的數字,但我想我可以在for循環中添加一些文本! :).....老實說,不能夠感謝你。我本來打算花一到兩週的時間! – ScoutEU

+1

不客氣,現在我猜你可以很容易地從組合中獲得標準偏差和其他結果。 – Eular

1

我upvoted最後的答案,但我還以爲我會告訴你,保持一切都在數據幀

data = """RefNumber, Reviewer 1, Reviewer 2,Reviewer 3,Reviewer 4,Reviewer 5 
9676/2,6,3,2,, 
0526/4,6,3,1,5,1 
1842/1,5,3,1,5, 
2693/3,5,5,1,2, 
2515/1,6,3,1,5,3 
2987/1,4,1,3,, 
3841/1,4,3,1,, 
3402/1,4,3,1,5, 
""" 

import pandas 
import itertools 
import StringIO 
import numpy 

buffer = StringIO.StringIO(data) 
df = pandas.read_csv(buffer, index_col=0) 

# EVERYTHING ABOVE IS MOSTLY SETUP CODE FOR THE EXAMPLE 
def get_combos(items, lower_bound=3): 
    """ 
    Return all combinations of values of size lower_bound 
    for items 
    """ 
    usable = items.dropna() 
    combos = list() 
    n_combos = range(lower_bound, len(usable) + 1) 
    for r in n_combos: 
     combos += list(itertools.combinations(usable, r)) 
    return combos 

df['combos'] = df.apply(get_combos, axis=1) 
df['means'] = df['combos'].map(lambda items: [numpy.mean(x) for x in items]) 
+0

非常感謝你:) – ScoutEU