Python Pandas—将CSV读入dataframe,其中一列具有不同数量的子列

Python Pandas—将CSV读入dataframe,其中一列具有不同数量的子列,python,pandas,dataframe,Python,Pandas,Dataframe,在Pandas中,是否可能有一个包含不同数量子列的列的数据帧 例如,假设我有以下CSV文件: transactionId, userName, date, itemList, totalCost 其中,itemList包含数量可变的itemId;itemPrice成对,成对之间用管道隔开(|)。itemId的数量没有上限;列表中的itemPrice对 itemId ; itemPrice | itemId ; itemPrice 以下是一些行的示例: transactionId, userN

在Pandas中,是否可能有一个包含不同数量子列的列的数据帧

例如,假设我有以下CSV文件:

transactionId, userName, date, itemList, totalCost
其中,
itemList
包含数量可变的
itemId;itemPrice
成对,成对之间用管道隔开(
|
)。
itemId的数量没有上限;列表中的itemPrice

itemId ; itemPrice | itemId ; itemPrice
以下是一些行的示例:

transactionId, userName, date,       itemList,              totalCost
123,           Bob  ,    7/29/2017,  ABC;10|XYZ;20,         30
234,           Alice,    7/31/2017,  CDE;20|QRS;15|KLM;10,  45
第一行有两个
itemId;itemPrice
对,而第二行有三对

如何创建包含此信息的数据框?我需要一个数据帧内的数据帧吗


在不同数量的列上还有其他Stackoverflow帖子,但是。

我会尝试规范化您的数据:


PS last empty DF表明我们没有任何
totalCost!=总和(价格)

您可以使用列表解析它们

d1 = df.assign(
    itemList=[[x.split(';') for x in y.split('|')] for y in df.itemList.tolist()]
)

d1

   transactionId userName       date                           itemList  totalCost
0            123      Bob  7/29/2017             [[ABC, 10], [XYZ, 20]]         30
1            234    Alice  7/31/2017  [[CDE, 20], [QRS, 15], [KLM, 10]]         45

评论回复

f = lambda x: np.array(x)[:, 1].astype(int).sum()

d1.assign(sumPrice=d1.itemList.apply(f))

   transactionId userName       date                           itemList  totalCost  sumPrice
0            123      Bob  7/29/2017             [[ABC, 10], [XYZ, 20]]         30        30
1            234    Alice  7/31/2017  [[CDE, 20], [QRS, 15], [KLM, 10]]         45        45

你可以考虑把它们存储为字典吗?如果你想每个单元(而不是字典)有一个单独的值,你应该决定是让表“宽”(每额外值增加一列)还是“高”(每额外值增加一行)。答案会根据你的选择而有所不同。@DYZ:我想我需要广泛的答案。例如,我的目标之一是审核
itemPrice
值的总和是否等于整行的
totalCost
。这是一个有趣的表示。我创建了这个数据框,并且
dataframe.info()
itemList
列的类型是
Object
。我如何迭代
itemList
中的项目来总结
itemPrice
值?我可以这么做,但我们已经走上了一条没有手电筒的黑暗道路。。。你确定要继续吗?我会坚持@MaxU答案中的高数据框。如果可以的话,包括我在内的很多读者都会很感激。“我正在试图理解所涉及的权衡,例如空间与编码复杂性。”stackoverflowuser2010添加了示例。谢谢。非常感谢。
d1 = df.assign(
    itemList=[[x.split(';') for x in y.split('|')] for y in df.itemList.tolist()]
)

d1

   transactionId userName       date                           itemList  totalCost
0            123      Bob  7/29/2017             [[ABC, 10], [XYZ, 20]]         30
1            234    Alice  7/31/2017  [[CDE, 20], [QRS, 15], [KLM, 10]]         45
f = lambda x: np.array(x)[:, 1].astype(int).sum()

d1.assign(sumPrice=d1.itemList.apply(f))

   transactionId userName       date                           itemList  totalCost  sumPrice
0            123      Bob  7/29/2017             [[ABC, 10], [XYZ, 20]]         30        30
1            234    Alice  7/31/2017  [[CDE, 20], [QRS, 15], [KLM, 10]]         45        45