2017-07-02 85 views
3

我想使用PyUpset封裝,它在PICKEL測試數據,可以發現here我們如何可以格式化數據這樣的泡菜

我可以運行下面的代碼來查看數據的內容和格式

from pickle import load 
with open('./test_data_dict.pckl', 'rb') as f: 
    data_dict = load(f) 
data_dict 

這表明數據是以下格式,它只是一個例子如何看起來像的,

[495 rows X 4 columns], 
    'adventure':   title rating_avg \ 
     0    20,000 Leagues Under the Sea (1954) 3.702609  
     1     7th Voyage of Sinbad, The (1958)  3.616279 

      rating_std views 
     0  0.869685 575 
     1  0.931531 258 

    [281 rows x 4 columns], 
    'romance':   title rating_avg \ 
     0    'Til There Was You (1997) 2.402609  
     1     1-900 (1994)    2.411279 

      rating_std views 
     0  0.669685 575 
     1  0.981310 245 

我一直在試圖格式化我的CSV數據以這種方式和最近我能夠用熊貓爲類似的格式如下這個

CSV文件,以獲得,

Type_A, Type_B, Type_C 
x1,x2,x3 
y1,y2,y3 

用於大熊貓在數據幀導入並添加索引後一起Concat的他們

import pandas as pd 
df=pd.read_csv(csv_file) 
d1=df.Type_A.tolist() 
d2=df.Type_B.tolist() 
d3=df.Type_C.tolist() 

然後添加索引用於枚舉()

d1_df=list(enumerate(d1, 1)) 
d2_df=list(enumerate(d2, 1)) 
d3_df=list(enumerate(d3, 1)) 
d1_df # this gives me [(1, 'x1'), (2, 'y1')] 

ñ嗷嗷接下來我加標貼標識和值,數據幀

labels = ['Id','Value'] 
d1_df = pd.DataFrame.from_records(d1_df, columns=labels) 
d2_df = pd.DataFrame.from_records(d2_df, columns=labels) 
d3_df = pd.DataFrame.from_records(d3_df, columns=labels) 


d1_df # this gives me Id Value 
     #   0 1 x1 
     #   1 2 y1 

然後合併所有的3成一個數據幀,並重新定義TYPE_A,TYPE_B和Type_C

child_df = [d1_df, d2_df, d3_df] 
labels2 = ['Type_A','Type_B','Type_C'] 

parent_df = pd.concat(child_df, keys=['Type_A', 'Type_B', 'Type_C']) 

parent_df # out below 


#   Id Value 
#Type_A 0 1 x1 
#  1 2 y1 
#Type_B 0 1 x2 
#  1 2 y2 
#Type_C 0 1 x3 
#  1 2 y3 

這是我打的,我想我使用錯誤的方法,它應該更容易以PyUpset使用的格式獲取數據。

回答

2

我認爲你需要轉置表格,以便它是'長'格式。一旦你這樣做了,你可以使用pandas中的groupby方法爲pyupset製作正確的字典。

import pandas as pd 
try: 
    # for Python 2.x 
    from StringIO import StringIO 
except ImportError: 
    # for Python 3.x 
    from io import StringIO 

test_string = StringIO("""Type_A,Type_B,Type_C 
x1,x2,x3 
y1,y2,y3""") 

df = pd.read_csv(test_string) 
df = pd.melt(df, var_name='type') 
# df now looks like this: 
# 
# type  value 
# 0 Type_A x1 
# 1 Type_A y1 
# 2 Type_B x2 
# 3 Type_B y2 
# 4 Type_C x3 
# 5 Type_C y3 

pyupset_data = {key: df.loc[value] for key, value in df.groupby("type").groups.items()} 
0

我認爲它實際上只是一個普通的Python字典,值就是整個dataframes。關鍵是你想要的最後一行的標題。

相關問題