[英]Python - CSV - All the permutations of each row of numbers into tuples
我是Python的新手,但可以學習。 我的工作任務是采用以下格式來處理CSV數據(2500行)(因為我們無法弄清楚如何在Excel中做到這一點):
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個)。
即
以上3841/1將產生{4,3,1}的元組,平均為2.7
上面的3402/1將產生{4,3,1},{4,3,1,5},{3,1,5},{4,1,5}等元組,平均為2.7、3.3 ,3、3.3等。
我動了腦筋,想着想辦法做到最好,因為我還需要知道每個平均值,它包含的元組中有多少個數字,即{4,3,1}的平均值為2.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條評論),並且只需將每個數據表放在自己的標簽上即可。
從技術上講,我還需要每個元組的標准偏差和分數范圍,但這已經超出了我的專業水平,因此我想我可以刪除它或以某種方式手動進行。
關於從哪里開始的任何想法?
您可以使用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))
我贊成最后一個答案,但我想向您展示一個將所有內容保留在DataFrame中的示例
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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.