我的示例数据如下所示:
data = {'index': ['001', '002', '003'],
'A' : ['red', 'green', 'blue'],
'B' : ['blue', 'yellow', 'green'],
'C' : ['green', 'blue', 'red'],
'A_new' : [2, 1, 3], 'B_new' : [0, 1, 2], 'C_new' : [0, 0, 1],
'A_old' : [1, 0, 1], 'B_old' : [1, 0, 0], 'C_old' : [0, 0, 2],
'A_other_new' : [2, 0, 1], 'A_other_old' : [1, 1, 0]}
df = pd.DataFrame (data, columns = ['index', 'A', 'B', 'C', 'A_new', 'B_new', 'C_new',
'A_old', 'B_old', 'C_old', 'A_other_new', 'A_other_old'])
df
输出:
index A B C A_new B_new C_new A_old B_old C_old A_other_new A_other_old
0 001 red blue green 2 0 0 1 1 0 2 1
1 002 green yellow blue 1 1 0 0 0 0 0 1
2 003 blue green red 3 2 1 1 0 2 1 0
我正在尝试'C'根据索引和其他列将列移动到行,但这非常困难,因为我只是一个初学者并正在学习 Pandas。关键是将列中的每个 +1 值移动到一个新行,'C'通过 columns 'index',连接到原始数据框。在 column 下,如果原始数据列or > 0,我需要为每个 +1 值标记(O 是字母,X 是数字)。这部分很重要,我不能跳过它,因为我需要做其他步骤。
'color''letter''reference''reference''A_other_new''A_other_old''OX'有人知道如何解决这个问题吗?
我想要的输出是:
index color letter reference age
00 001 red A A1 new
01 001 red A A2 new
02 001 red A A3 old
03 001 red A O1 new
04 001 red A O2 new
05 001 red A O3 old
06 001 blue B B1 old
07 001 green C C1 0
08 002 green A A1 new
09 002 green A O1 old
10 002 yellow B B1 new
11 002 blue C C1 0
12 003 blue A A1 new
13 003 blue A A2 new
14 003 blue A A3 new
15 003 blue A A4 old
16 003 blue A O1 new
17 003 green B B1 new
18 003 green B B2 new
19 003 red C C1 new
20 003 red C C2 old
21 003 red C C3 old