python - SQL 输出到列表

标签 python pandas

我有一个这种格式的 csv

ORDER_ID    Item_DESC
 121    Beer
 121    Chips
 121    Wine
 141    Chips
 141    Wine

我需要以这种格式推出它:

121    Beer,Chips,Wine
141    Chips,Wine

有人能给我指出正确的方向吗,我已经伤透了一周了。

我尝试了以下方法:

Excel Pandas-枢轴、堆叠、熔化 SQL 中的递归表

感谢任何帮助。

最佳答案

您可以使用groupby and apply :

In [11]: df
Out[11]:
   ORDER_ID Item_DESC
0       121      Beer
1       121     Chips
2       121      Wine
3       141     Chips
4       141      Wine

In [12]: df.groupby("ORDER_ID")["Item_DESC"].apply(",".join)
Out[12]:
ORDER_ID
121         Beer,Chips,Wine
141              Chips,Wine
Name: Item_DESC, dtype: object

然后使用 to_csv就这个结果而言。

关于python - SQL 输出到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29909472/

相关文章:

python - 保存到文件时Dask崩溃?

python - 如何在列上添加标题

python - Pandas - 处理分类数据中的 NaN

python - Spark DataFrame 运算符(唯一、乘法)

python - 从 pandas DataFrame 中的分组数据绘制直方图

python - 将 csv 转换为 JSON 树结构?

python-3.x - Matplotlib 通过循环为 y 刻度标签着色

python - 如何从 DataFrame TimeIndex 中提取频率

python - OpenCV BGR 和 PyPlot RGB

Python解释器等待子进程死亡