[英]Creating a Dataframe with special special format
在接下来的条件下创建数据框的最佳方法是什么?
我有一个带有单个列的数据框,有几个家庭,每个家庭下面都有一些项目说明,一些家庭有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)
我想获得一个包含两列的数据框
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
因此,我可以通过[在线]提示来识别家庭物品,并且每个家庭都有不同数量的物品。
什么是更Python的方式来解决这个问题?
鉴于您的初始数据帧如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.