Python:转换dataframe,使索引和列ID成为行的元素
我发现这很难说,但基本上我想重新组织一个数据框架,使索引和列ID成为数据框架的元素。下面是一个例子:Python:转换dataframe,使索引和列ID成为行的元素,python,pandas,Python,Pandas,我发现这很难说,但基本上我想重新组织一个数据框架,使索引和列ID成为数据框架的元素。下面是一个例子: import numpy as np import pandas as pd # set seed np.random.seed(420) # make example dataframe df1 = pd.DataFrame(data=np.random.randint(1, 9, size=(4,4)), index=['a','b','c','d'], columns=['a'
import numpy as np
import pandas as pd
# set seed
np.random.seed(420)
# make example dataframe
df1 = pd.DataFrame(data=np.random.randint(1, 9, size=(4,4)),
index=['a','b','c','d'], columns=['a','b','c','d'])
In [1]: df1
Out[1]:
a b c d
a 2 1 7 8
b 8 4 7 2
c 3 3 1 7
d 8 7 7 5
我想把数据框重新组织成这样
id1 id2 value
1 a a 2
2 a b 1
3 a c 7
4 a d 8
5 b a 8
6 b b 4
7 b c 7
8 b d 2
9 c a 3
10 c b 3
11 c c 1
12 c d 7
13 d a 8
14 d b 7
15 d c 7
16 d d 5
请随意编辑我问题的标题,以便更好地反映我的问题。正如我所说,我发现很难说出我想做什么。谢谢 用于:
Numpy解决方案包括,以及:
完美的非常感谢。顺便说一下,我觉得我对这个问题的措辞不是很好。您如何描述这种数据重组?您知道这个问题是否重复吗?@Lachlan.00-是的,这类问题很难找到,但我发现已经找到了重复。谢谢@sai,我很快会标记为重复。
df1 = df.stack().reset_index()
df1.columns = ['id1','id2','value']
print (df1)
id1 id2 value
0 a a 2
1 a b 1
2 a c 7
3 a d 8
4 b a 8
5 b b 4
6 b c 7
7 b d 2
8 c a 3
9 c b 3
10 c c 1
11 c d 7
12 d a 8
13 d b 7
14 d c 7
15 d d 5
a = np.repeat(df.index, len(df.columns))
b = np.tile(df.columns, len(df))
c = df.values.ravel()
df1 = pd.DataFrame({'id1':a,'id2':b,'value':c})