Python:转换数据集

标签 python python-2.7 pandas

我有以下数据集

            id  type  value
0             1   A    10
1             1   C   120
2             2   B    20
3             2   C    40
4             3   A    10
5             3   B    50

我想在Python中将其转换为(1,A,10,C,120) (2,B,20,C,40) (3,A,10,B,50)

如有任何建议,我们将不胜感激

最佳答案

id列执行groupby。通过将其他两列转换为列表来迭代每个组,并添加与每个组编号对应的唯一值。最后,将它们转换为元组并将它们附加到列表中。

grouped = df.groupby('id')
L = []
for _, grp in grouped:
    L.append(tuple(grouped.get_group(_)['id'].unique().tolist() + grp[['type','value']].values.ravel().tolist()))
print(L)
#[(1, 'A', 10, 'C', 120), (2, 'B', 20, 'C', 40), (3, 'A', 10, 'B', 50)]

关于Python:转换数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40535163/

相关文章:

python - Tkinter标签删除时的Python OpenCV输出

python - 如何用 Pandas 数据框中第一行和相应行之间的列的平均值填充特定值

python - 执行网格搜索后分配模型参数

python - 属性错误: 'Series' object has no attribute 'org' when trying to filter a dataframe

python - Google Admin SDK 客户端库生成 SSL3_GET_RECRD :wrong version number error when attempting to get a user

Mysql 在 python 中显示类型错误

python - Pandas DataFrame 的自定义方法

python - Pandas 按工作日分组 (M/T/W/T/F/S/S)

python - 使用 Pandas 操作 CSV 文件 : Identifying a value in a column and using data from other columns of the same row

python - python 字典中的 for 循环