2016-11-20 116 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