python pandas,某些列到行 [英] python pandas, certain columns to rows

查看:72
本文介绍了python pandas,某些列到行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,有4行4列-这是asimple版本:

I have a pandas dataframe, with 4 rows and 4 columns - here is asimple version:

import pandas as pd
import numpy as np
rows = np.arange(1, 4, 1)
values = np.arange(1, 17).reshape(4,4)
df = pd.DataFrame(values, index=rows, columns=['A', 'B', 'C', 'D'])

我想做的是将其转换为2 * 8数据帧,每个数组具有B,C和D标识-因此它看起来像这样:

what I am trying to do is to convert this to a 2 * 8 dataframe, with B, C and D alligng for each array - so it would look like this:

1  2 
1  3
1  4
5  6
5  7
5  8
9  10
9  11
9  12
13 14
13 15
13 16

在阅读熊猫文档时,我尝试了以下方法:

reading on pandas documentation I tried this:

df1 = pd.pivot_table(df, rows = ['B', 'C', 'D'], cols = 'A')

但是给我一个错误,我无法识别来源(以

but gives me an error that I cannot identify the source (ends with

DataError:没有要聚合的数字类型

DataError: No numeric types to aggregate

)

接下来,我想根据A值分割数据框,但我认为.groupby命令可能会解决这个问题

following that I want to split the dataframe based on A values, but I think the .groupby command is probably going to take care of it

推荐答案

您正在寻找的是

What you are looking for is the melt function

 pd.melt(df,id_vars=['A']) 

     A variable  value
0    1        B      2
1    5        B      6
2    9        B     10
3   13        B     14
4    1        C      3
5    5        C      7
6    9        C     11
7   13        C     15
8    1        D      4
9    5        D      8
10   9        D     12
11  13        D     16

然后必须根据A进行最终排序

A final sorting according to A is then necessary

 pd.melt(df,id_vars=['A']).sort('A')  

      A variable  value
 0    1        B      2
 4    1        C      3
 8    1        D      4
 1    5        B      6
 5    5        C      7
 9    5        D      8
 2    9        B     10
 6    9        C     11
 10   9        D     12
 3   13        B     14
 7   13        C     15
 11  13        D     16

注意:pd.DataFrame.sort 已弃用赞成pd.DataFrame.sort_values.

这篇关于python pandas,某些列到行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆