我正在处理以下数据,最终我不想在变量名称中使用旧/新,而是想比较旧 x 与新 x、旧 y 与新 y 等,其中旧的和新的包含在“年龄”变量中。
np.random.seed(5)
dat = []
for r in range(100):
v = np.random.rand(6)
rec = {
"i": r,
"old_x": v[0],
"old_y": v[1],
"old_z": v[2],
"new_x": v[3],
"new_y": v[4],
"new_z": v[5],
}
dat.append(rec)
df = pd.DataFrame(dat)
>>> df
i old_x old_y old_z new_x new_y new_z
0 0 0.110519 0.096792 0.980107 0.156369 0.540795 0.358307
1 1 0.292648 0.623699 0.376485 0.271227 0.931222 0.391800
2 2 0.872280 0.412259 0.831854 0.417520 0.874671 0.267805
3 3 0.497580 0.342821 0.338618 0.447617 0.618905 0.630221
4 4 0.611636 0.413489 0.302103 0.855590 0.061317 0.155975
.. .. ... ... ... ... ... ...
95 95 0.798706 0.085928 0.215995 0.819614 0.074777 0.876801
96 96 0.997671 0.344107 0.335971 0.199516 0.238919 0.852654
97 97 0.437936 0.924561 0.668733 0.148862 0.166350 0.861785
98 98 0.822570 0.426939 0.935153 0.771598 0.555669 0.639590
99 99 0.849823 0.960070 0.437960 0.675045 0.745331 0.428660
[100 rows x 7 columns]
我想将其 reshape 为 columns = ["age", "x", "y", "z"]
给出的数据框,其中 age 取值 ["旧”, "new"]
.
这是我尝试过的:
>>> pd.wide_to_long(df, stubnames=['old',"new"], i='i', j='age', sep='_', suffix=r'\w+')
old new
i age
0 x 0.110519 0.156369
1 x 0.292648 0.271227
2 x 0.872280 0.417520
3 x 0.497580 0.447617
4 x 0.611636 0.855590
... ... ...
95 z 0.215995 0.876801
96 z 0.335971 0.852654
97 z 0.668733 0.861785
98 z 0.935153 0.639590
99 z 0.437960 0.428660
[300 rows x 2 columns]
您可以看到这与我正在寻找的有点相反。这也没有用:
df.pivot_table(values=["x", "y", "z"], index=[i], columns='age')
KeyError: 'x'
我正在寻找的更像是:
>>> df
i x y z age
0 0 0.110519 0.096792 0.980107 old
0 0.156369 0.540795 0.358307 new
1 1 0.292648 0.623699 0.376485 old
1 0.271227 0.931222 0.391800 new
2 2 0.872280 0.412259 0.831854 old
2 0.417520 0.874671 0.267805 new
如果“旧”和"new"是 bool 值而不是字符串,我没问题。
最佳答案
另一种选择:
df.set_index(['i'], inplace=True)
df.columns = df.columns.str.split('_').map(tuple)
df.stack(level=0).rename_axis(('i', 'age')).reset_index()
# i age x y z
#0 0 new 0.918611 0.488411 0.611744
#1 0 old 0.221993 0.870732 0.206719
#2 1 new 0.187721 0.080741 0.738440
#3 1 old 0.765908 0.518418 0.296801
#4 2 new 0.274086 0.414235 0.296080
#.. .. ... ... ... ...
#195 97 old 0.960385 0.784069 0.922694
#196 98 new 0.056743 0.165556 0.430358
#197 98 old 0.460486 0.734635 0.953751
#198 99 new 0.174529 0.041988 0.635096
#199 99 old 0.027449 0.359603 0.423178
#[200 rows x 5 columns]
关于python - 从宽到长,但我想使用前缀而不是后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67170315/