【问题标题】:re and pandas, reshaping listsre 和 pandas,重塑列表
【发布时间】:2018-01-05 14:14:15
【问题描述】:

我有一个列表格式为:

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) 列中。

【问题讨论】:

标签: python list pandas


【解决方案1】:

可以这样做,

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]

【讨论】:

  • 如何进一步拆分它,使每个 P 值都是一个单独的字符串,但仍然在同一行?这样 002 会有两个 Product_Id 字符串而不是一个?另外如何将索引标记为“transaction_id”?
  • 'code'(df.set_idex(['transaction_id'],inplace=True])) 中有一个错字,因为有一个额外的 ] 但代码有效,谢谢!现在-我必须基于此 Dataframe 创建一个矩阵,如果产品在特定的篮子中,则为 1,否则为 0(对于“P1-P10”列)你知道我该怎么做吗?
  • 这完全是另一个问题,我会研究一个hot encoding
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 2014-07-16
相关资源
最近更新 更多