Python, Pandas, DataFrame, 行转列

2024-05-29 04:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个组织混乱的SQL表中提取了一个数据帧。该表对每个通道都有唯一的行 我可以将这些信息提取到python数据帧中,并打算进行进一步的处理,但现在只想将其转换为更有用的格式

样本输入:

C = pd.DataFrame()
A = np.array([datetime.datetime(2016,8,8,0,0,1,1000),45,'foo1',1])
B = pd.DataFrame(A.reshape(1,4),columns = ['date','chNum','chNam','value'])
C = C.append(B)
A = np.array([datetime.datetime(2016,8,8,0,0,1,1000),46,'foo2',12.3])
B = pd.DataFrame(A.reshape(1,4),columns = ['date','chNum','chNam','value'])
C = C.append(B)
A = np.array([datetime.datetime(2016,8,8,0,0,2,1000),45,'foo1',10])
B = pd.DataFrame(A.reshape(1,4),columns = ['date','chNum','chNam','value'])
C = C.append(B)
A = np.array([datetime.datetime(2016,8,8,0,0,2,1000),46,'foo2',11.3])
B = pd.DataFrame(A.reshape(1,4),columns = ['date','chNum','chNam','value'])
C = C.append(B)

生产

^{pr2}$

我想要

                                 date foo1     foo2  
2016-08-08 00:00:01.001000           1     12.3
2016-08-08 00:00:02.001000           10   113

我有一个解决方案:列出一个唯一的日期列表,为每个日期循环通过数据帧,并拉出每个通道,形成一个新行。有点乏味(容易出错)!所以我想知道有没有更好的方法来利用Pandas工具


Tags: columns数据dataframedatetimedatevaluenparray
1条回答
网友
1楼 · 发布于 2024-05-29 04:09:40

使用set_index然后使用unstack旋转

C.set_index(['date', 'chNum', 'chNam'])['value'].unstack(['chNam', 'chNum'])

enter image description here


为了得到你想要的东西

^{pr2}$

enter image description here

相关问题 更多 >

    热门问题