2015-07-01 32 views
0

我有一個具有以下格式的CSV文件。想象一下,白色空格用逗號分隔。來自具有多個標識符的元素的熊貓數據框格式

        slot0       slot1 
Serial  Timestamp  Height  Width  Score  Height  Width  Score .... 
FA125  2015_05  215.00  125.01 156.02 235.23  862.23 135.52 .... 

這種情況持續發生數千行,並重復使用這種模式的許多槽#。插槽號與它所居中的「高度,寬度和分數」相關聯。也就是說,slot0對應於第一個高度,寬度和分數,slot1對應於第二個高度,寬度和分數。每個插槽有三個測量。

我無法找到將此數據粘貼到pandas.DataFrame中的最佳方法,我將槽號與特定高度,寬度和分數相關聯,但尤其是串行或時間戳。

我曾經想過的一件事就是這樣的事情,但是如果我能做得更好,還不太清楚。

Serial  Timestamp s0_Height s0_Width s0_Score s1_Height s1_Width s1_score .... 
FA125  2015_05 215.00  125.01 156.02  235.23  862.23 135.52 .... 

這種形式似乎有點誇張,但如果這是我想我可以管理的唯一方法。

# Maybe something like this? 
pd.DataFrame({'FSJ1503007N-ct0': ['20150311_021738', 140, 123, 213]}, ['timestamp', 's0_height', 's0_score', 's0_width']) 

請記住,我可以以任何方式來實例化數據框適應CSV,但問題是它我不知道創建與此數據的數據框的最佳方式。

謝謝!

回答

1
import pandas as pd 
import numpy as np 
# just to create a string buffer, you don't need this if you have csv file 
from io import StringIO 

# replicate your csv file structure 
line1 = ','.join(['slot' + str(x) for x in range(3)]) + '\n' 
line2 = 'Serial,Timestamp,' + ','.join(['Height', 'Width', 'Score']*3) + '\n' 
np.random.seed(0) 
data = np.random.randint(100, 1000, size=9) 
line3 = 'FA125,2015_5,'+','.join([str(x) for x in data]) + '\n' 
csv_buffer = line1+line2+line3 

Out[40]: 'slot0,slot1,slot2\nSerial,Timestamp,Height,Width,Score,Height,Width,Score,Height,Width,Score\nFA125,2015_5,784,659,729,292,935,863,807,459,109\n' 


# read your file, set the first 2 columns as index, the rest using multi-level column index 
level1 = ['slot'+str(x) for x in range(3)] 
level2 = ['Height', 'Width', 'Score'] 
multi_level_columns = pd.MultiIndex.from_product([level1, level2]) 

df = pd.read_csv(StringIO(csv_buffer), index_col=[0,1], skiprows=[0], header=0) 
df.columns = multi_level_columns 

Out[62]: 
        slot0    slot1    slot2    
       Height Width Score Height Width Score Height Width Score 
Serial Timestamp               
FA125 2015_5  784 659 729 292 935 863 807 459 109 

# you can reshape the original df 
df.stack(level=0) 

Out[63]: 
         Height Score Width 
Serial Timestamp        
FA125 2015_5 slot0  784 729 659 
       slot1  292 863 935 
       slot2  807 109 459 
+0

ohh我喜歡這個! – Matt

1

這實際上取決於您想要對數據進行什麼樣的計算。

Serial Timestamp Height Width Score Height.1 Width.1 Score.1 .... 
0 FA125 2015_05  215 125.01 156.02 235.23 862.23 135.52 .... 

這可能足以滿足您的需求:

如果你直接跳過第一行,您的CSV將被讀入。

相關問題