Python 基于多个ID转换数据帧,并将两列拆分为一系列列
我有以下数据:Python 基于多个ID转换数据帧,并将两列拆分为一系列列,python,python-3.x,Python,Python 3.x,我有以下数据: import pandas as pd data = {'origin': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'destination': [2, 2, 2, 2, 2, 2, 3, 3, 3, 3], 'set': [1, 1, 1, 2, 2, 2, 1, 1, 1, 1], 'pointA': [1, 11, 12, 1, 11, 13, 1, 16, 17, 18], 'pointB': [11, 12, 2
import pandas as pd
data = {'origin': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
'destination': [2, 2, 2, 2, 2, 2, 3, 3, 3, 3],
'set': [1, 1, 1, 2, 2, 2, 1, 1, 1, 1],
'pointA': [1, 11, 12, 1, 11, 13, 1, 16, 17, 18],
'pointB': [11, 12, 2, 11, 13, 2, 16, 17, 18, 3],
'time': [5, 6, 5, 5, 5, 7, 8, 7, 3, 4]}
datainput = pd.DataFrame(data, columns = ['origin','destination','set', 'pointA', 'pointB', 'time'])
看起来是这样的:
origin destination set pointA pointB time
1 2 1 1 11 5
1 2 1 11 12 6
1 2 1 12 2 5
1 2 2 1 11 5
1 2 2 11 13 5
1 2 2 13 2 7
1 3 1 1 16 8
1 3 1 16 17 7
1 3 1 17 18 3
1 3 1 18 3 4
origin destination set point1 point2 point3 point4 point5 time
1 2 1 1 11 12 2 0 16
1 2 2 1 11 13 2 0 17
1 3 1 1 16 17 18 3 22
我希望在总结时间的同时将pointA和pointB列转换为一系列点,即每个唯一的[origin,destination,set]有一行,因此期望的输出如下所示:
origin destination set pointA pointB time
1 2 1 1 11 5
1 2 1 11 12 6
1 2 1 12 2 5
1 2 2 1 11 5
1 2 2 11 13 5
1 2 2 13 2 7
1 3 1 1 16 8
1 3 1 16 17 7
1 3 1 17 18 3
1 3 1 18 3 4
origin destination set point1 point2 point3 point4 point5 time
1 2 1 1 11 12 2 0 16
1 2 2 1 11 13 2 0 17
1 3 1 1 16 17 18 3 22
首先,我尝试了pivot函数,如下所示:
pivot=datainput.pivot_表(索引=['origin'、'destination'、'set'],值=['time'],aggfunc='sum')。重置_索引()
这可以得到唯一[起点、终点、集合]的时间和。然而,我正在努力将点A和点B添加到图片中,即点1、点2等
我已经探索了转置的潜力:
transposedData = datainput.T
但这只是转置数据帧,最终许多[源、目的地、集]被转置到列中。考虑到唯一的[origin,destination,set]的最大点数也是未知的,在这里我使用5作为数据样本,但是,我的输入文件将非常庞大,我不知道最大点数是多少
你知道怎么做吗?有关方法的阅读链接也将不胜感激
谢谢大家! 这应该可以做到:
将numpy导入为np
datainput[“pointC”]=列表(zip(datainput[“pointA”]、datainput[“pointB”]))
res=pd.pivot_table(datainput,index=[“origin”,“destination”,“set”],aggfunc=lambda x:(np.unique(np.hstack(x.values.ravel()).astype(str)).tolist(),values=[“pointC”]).pointC.apply(pd.Series).fillna(0).reset_index()
输出:
起点-终点集0 1 2 3 4
0 1 2 1 1 11 12 2 0
1 1 2 2 1 11 13 2 0
2 1 3 1 1 16 17 18 3
[程序完成]