简体   繁体   English

如何将具有相同 id 的行中的值转换为一个列表? (蟒蛇中的熊猫)

[英]How to convert the values in the row with same id to one list? (Pandas in python)

I uploaded the csv file我上传了csv文件

#Open the first dataset
train=pd.read_csv("order_products__train.csv",index_col="order_id")

The data looks like:数据看起来像:

         product_id
order_id                 
1              1
1              2
1              3
1              4
2              1
2              2
2              3
2              4
2              5
2              6       

What I want is the data frame looks like,我想要的是数据框的样子,

order_id       product_id
1              1,2,3,4
2              1,2,3,4,5,6

Since I want to generate a list like因为我想生成一个列表

[[1,2,3,4],[1,2,3,4,5,6]]

Could anyone help?有人能帮忙吗?

You can use the the function .groupby() to do that您可以使用 function .groupby()来做到这一点

train = train.groupby(['order_id'])['product_id'].apply(list)

That would give you expected output:这会给你预期的 output:

order_id
1       [1, 2, 3, 4]
2    [1, 2, 3, 4, 5]

Finally, you can cast this to a DataFrame or directly to a list to get what you want:最后,您可以将其转换为 DataFrame 或直接转换为列表以获得您想要的内容:

train = train.to_frame()  # To pd.DataFrame
# Or
train = train.to_list()  # To nested lists [[1,2,3,4],[1,2,3,4,5]]

There must be better ways but I guess you can simply do the following:必须有更好的方法,但我想你可以简单地执行以下操作:

list_product = []
for i in train["order_id"].unique():
  tmp = train[train["order_id"] == i]
  list_product.append(tmp["product_id"].to_list())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 pandas 将多行转换为同一 ID 的单行 - how to convert multiple rows into single row for same id using pandas Python Pandas:列出每一行具有相同值的列 - Python Pandas: list columns with the same values for each row 如何将一列的每一行值转换为pandas中的列表? - How to convert each row values of a column to a list in pandas? Pandas 合并具有相同 id 行的列表 - Pandas merge list with same id row wise Python:如何将 Pandas Dataframe 行值转换为单个列? - Python: How to convert Pandas Dataframe Row Values to individual columns? Python:如何将 Pandas Dataframe 行值转换为单个列? - Python: How to convert Pandas Dataframe Row Values to individual columns? 如何将具有相同索引(MultiIndex之一)的行值转换为列 - How to convert row values with same index(one of the MultiIndex) into columns 将具有相同ID的多行(具有一些非字符串值)合并到熊猫的一个定界行中 - Merge multiple rows (having some non string values) with same ID into one delimited row in pandas Python/Pandas:如果 Column 有多个值,则转换为列表中包含多个值的单行 - Python/Pandas: If Column has multiple values, convert to single row with multiples values in list 如何为python / pandas中的值列表提取列和行数据 - How to pull column and row data for a list of values in python/pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM