2017-07-29 110 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