python pandas,某些列到行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19842066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python pandas, certain columns to rows
提问by Dimitris
I have a pandas dataframe, with 4 rows and 4 columns - here is asimple version:
我有一个 Pandas 数据框,有 4 行和 4 列 - 这是一个简单的版本:
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'])
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:
我想要做的是将其转换为 2 * 8 数据帧,每个数组的 B、C 和 D 对齐 - 所以它看起来像这样:
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:
阅读Pandas文档我试过这个:
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: No numeric types to aggregate
DataError:没有要聚合的数字类型
)
)
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
接下来我想根据 A 值拆分数据帧,但我认为 .groupby 命令可能会处理它
回答by Acorbe
What you are looking for is the meltfunction
您正在寻找的是melt功能
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 final sorting according to Ais then necessary
最后的排序根据A然后是必要的
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
Note: pd.DataFrame.sorthas been deprecatedin favour of pd.DataFrame.sort_values.
注意:pd.DataFrame.sort已被弃用而支持pd.DataFrame.sort_values.

