【发布时间】:2021-03-03 16:45:35
【问题描述】:
我正在尝试使用 pandas 将列转换为多行。我在数据库中的下表中有数据。下面附上csv格式
CustomerID,Expiry_Date,ProductA,ProductAType,ProductB,ProductBType,ProductC,ProductCType,ProductD,ProductDType,ProductF,ProductFType,ProductG,ProductGType
1,22/11/2020,YES,Trial,NO,Nan,NO,Nan,NO,Nan,YES,Full,NO,Nan
2,30/12/2020,NO,Nan,YES,Full,NO,Nan,NO,Nan,NO,Nan,NO,Nan
3,01/12/2020,NO,Nan,NO,Nan,YES,Full,YES,Trial,NO,Nan,NO,Nan
这是作为数据框的示例数据。
import pandas as pd
import csv
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
TESTDATA = StringIO("""CustomerID,Expiry_Date,ProductA,ProductAType,ProductB,ProductBType,ProductC,ProductCType,ProductD,ProductDType,ProductF,ProductFType,ProductG,ProductGType
1,22/11/2020,YES,Trial,NO,Nan,NO,Nan,NO,Nan,YES,Full,NO,Nan
2,30/12/2020,NO,Nan,YES,Full,NO,Nan,NO,Nan,NO,Nan,NO,Nan
3,01/12/2020,NO,Nan,NO,Nan,YES,Full,YES,Trial,NO,Nan,NO,Nan""")
df=pd.read_csv(TESTDATA, sep=",", quoting=csv.QUOTE_NONE)
该表包含大约 50 列的列表,“是”和“否”选项是客户购买了该产品。
如果客户拥有它及其类型,我需要将行转置为列并输出客户、expiry_id 和带有 Product_name 的 product_column。如下。
CustomerID,Expiry_Date,Product,Type
1,22/11/2020,ProductA,Trial
1,22/11/2020,ProductF,Full
2,30/12/2020,ProductB,Full
3,01/12/2020,ProductC,Full
3,01/12/2020,ProductD,Trial
最后两列也可以是一个连接列
CustomerID,Expiry_Date,Product
1,22/11/2020,ProductA-Trial
1,22/11/2020,ProductF-Full
2,30/12/2020,ProductB-Full
3,01/12/2020,ProductC-Full
3,01/12/2020,ProductD-Trial
知道如何在 pandas 或 sql 中实现这一点吗?
【问题讨论】: