列表的矩陣我有一個CSV文件和項目的列表,每個都連有一系列屬性:創建從屬性
"5","coffee|peaty|sweet|cereal|cream|barley|malt|creosote|sherry|sherry|manuka|honey|peaty|peppercorn|chipotle|chilli|salt|caramel|coffee|demerara|sugar|molasses|spicy|peaty"
"6","oil|lemon|apple|butter|toffee|treacle|sweet|cola|oak|cereal|cinnamon|salt|toffee"
「5」和「6」都是項目ID和獨特在文件中。
最終,我想創建一個矩陣,演示文檔中每個屬性在同一行中提及的每個屬性的次數。例如:
peaty sweet cereal cream barley ...
coffee 1 2 2 1 1
oil 0 1 0 0 0
請注意,我寧願減少重複項,即「peaty」不是列和行都是。
原始數據庫本質上是一個鍵值存儲(一個包含「itemId」和「value」列的表) - 如果有幫助,我可以重新格式化數據。
任何想法如何使用Python,PHP或Ruby(無論哪個最簡單)做到這一點?我感覺Python可以做到這一點是最簡單的,但我錯過了一些相當基本和/或至關重要的東西(我剛剛開始用Python進行數據分析)。
謝謝!
編輯:爲響應(有點無益的)「你嘗試過什麼」的評論,這裏就是我目前正與(別笑,我的Python是可怕的):
#!/usr/bin/python
import csv
matrix = {}
with open("field.csv", "rb") as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
attribs = row[1].split("|")
for attrib in attribs:
if attrib not in matrix:
matrix[attrib] = {}
for attrib2 in attribs:
if attrib2 in matrix[attrib]:
matrix[attrib][attrib2] = matrix[attrib][attrib2] + 1
else:
matrix[attrib][attrib2] = 1
print matrix
輸出是一個很大的未排序的術語詞典,可能在行和列之間有很多重複。如果我用熊貓和替換爲以下「打印矩陣」行......
from pandas import *
df = DataFrame(matrix).T.fillna(0)
print df
我得到:
<class 'pandas.core.frame.DataFrame'>
Index: 195 entries, acacia to zesty
Columns: 195 entries, acacia to zesty
dtypes: float64(195)
...這使我覺得我做的東西,而錯。
[你有什麼試過?](http://mattgemmell.com/2008/12/ 08/what-you-you-tried /) – martineau
泥炭必須既是一排又是一列,否則你如何將它與甜和咖啡比較? – njzk2
@ njzk2我想這是有道理的。我最終想要將它插入一個線圖中,而不是想讓一根線回到自己身上。見:http://circos.ca/guide/tables/img/guide-table-large。png – aendrew