2016-11-20 52 views
0

爲下一個條件創建數據幀的最佳方法是什麼?創建特殊格式的數據幀

我有一個Dataframe與一個單欄,有幾個家庭,每個家庭下面有一些項目說明,有些家庭有3個項目,其中一些有7個,唯一的提示識別家庭是由「 [在線]「字符串。

0 Family Item1[online] 
1 Description of the Item1 (SKU) 
2 Description of the Item1 (SKU) 
3 Description of the Item1 (SKU) 
4 Family Item2[online] 
5 Description of the Item2 (SKU) 
6 Description of the Item2 (SKU) 
7 Description of the Item2 (SKU) 
................................ 
n-3Family Itemk[online] 
n-2 Description of the Itemk (SKU) 
n-1 Description of the Itemk (SKU) 
n Description of the Itemk (SKU) 

,我想獲得一個數據幀2列

Column1 Column2 
0 Family Item1 Description Item1 
1 Family Item1 Description Item1 
2 Family Item1 Description Item1 
3 Family Item2 Description Item2 
.................................. 
n Family Itemk Description Itemk 

所以我的線索[在線],以確定家庭項和每個家庭都有不同數量的項目。

什麼是更pythonic的方式來解決這個問題?

+0

請問您能澄清一下,您的輸入數據是什麼?它是Python列表還是文件,或者是什麼?什麼是「Item1(SKU)的說明」?輸入和期望的輸出數據的簡單例子將非常感謝。 –

+0

這是隻有一列的數據框 –

+0

您已經留下了太多未解答的問題。家庭是否總是按照四個,一個家庭項目和三個描述分組?如果不是,「家庭」一詞實際上是真實數據中的單詞嗎?意思是,我們可以編寫代碼來搜索單詞「家庭」嗎?或者你會說,「哦,這不會工作,因爲你看,我的數據實際上看起來像我現在沒有提到的其他事情。」你看我要去哪裏?這太模糊了。 – piRSquared

回答

0

鑑於你的初始數據幀是這樣的:

import pandas as pd 

df = pd.DataFrame(data=['Family Item1[online]', 
         'Description of the Item1 (SKU)', 
         'Description of the Item1 (SKU)', 
         'Description of the Item1 (SKU)', 
         'Family Item2[online]', 
         'Description of the Item2 (SKU)', 
         'Description of the Item2 (SKU)', 
         'Description of the Item2 (SKU)',],index=np.arange(0,8)) 

dict_i = {} 
key = None 

for item in df[0].values: 

    if '[online]' in item: 
     key = item 
     dict_i[key] = [] 
    else: 
     dict_i[key].append(item) 
pd.DataFrame(dict_i) 

其中給出:

   Family Item1[online]   Family Item2[online] 
0 Description of the Item1 (SKU) Description of the Item2 (SKU) 
1 Description of the Item1 (SKU) Description of the Item2 (SKU) 
2 Description of the Item1 (SKU) Description of the Item2 (SKU) 

如果該系列是不一樣的長度:

series_list = [] 
for k, v in dict_i.items(): 
    s = pd.Series(data=v,name=k) 
    series_list.append(s) 

pd.concat(series_list,axis=1) 

這會導致具有缺失值的數據幀的長度不匹配。

   Family Item1[online]   Family Item2[online] 
0 Description of the Item1 (SKU) Description of the Item2 (SKU) 
1 Description of the Item1 (SKU) Description of the Item2 (SKU) 
2 Description of the Item1 (SKU) Description of the Item2 (SKU) 
3 Description of the Item1 (SKU)        NaN 
4 Description of the Item1 (SKU)        NaN