2017-07-29 73 views
-2

我有一个列表的列表格式为:再和熊猫,重塑名单

testing_set = ["001,P01", "002,P01,P02", "003,P01,P02,P09", "004,P01,P03"] 

我以前re重新格式化列表,例如:

[in] test_set1 = [ re.split(r',', line, maxsplit=5) for line in testing_set] 

[out] ["001","P01"] 

如何创建一个数据帧,其中索引是(transaction_id)“001,002,003,004”,每行的p值列在列(product_id)中。

+0

您的名单列表...你的意思是一个字符串列表? – DJK

+0

这是一个字符串列表列表 – zsad512

+0

请阅读[如何制作好可重复的熊猫示例](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)并编辑相应地发布你的文章。 – MaxU

回答

0

这可以这样做,

testing_set = ["001,P01","002,P01,P02","003,P01,P02,P09","004,P01,P03"] 

test_set1 = [re.split(r',', line, maxsplit=1) for line in testing_set] 
#change maxsplit to 1______________________^ 

df =pd.DataFrame(test_set1,columns=['transaction_id','product_id']) 
df.set_index(['transaction_id'],inplace=True) 
df['product_id'] = df['product_id'].apply(lambda row: row.split(',')) 

它给你一个数据帧像这样

     Product_id 
transaction_id     
001      [P01] 
002     [P01, P02] 
003    [P01, P02, P09] 
004     [P01, P03] 
+0

我怎样才能进一步分割它,使每个P值是一个单独的字符串,但仍然在同一行?所以002会有两个Product_Id字符串而不是一个?另外我怎样才能将索引标记为“transaction_id”? – zsad512

+0

@ zsad512,我已更新代码 – DJK

+0

'代码'中存在一个错字(df.set_idex(['transaction_id'],inplace = True])),因为还有一个额外的代码],但代码正常工作,谢谢!现在,我必须根据这个数据框创建一个矩阵,如果产品在特定的篮子中,则为1,否则为0(对于列“P1-P10”),你知道我该怎么做吗? – zsad512