我从一个EXCEL表中引入调查数据,其中有多个列在EXCEL表中具有相同的标题,当我将它们导入到我的数据框中时,它们被重新格式化为Value1、Value2、Value.3等.
我一直在try 将数据帧从宽格式更改为长格式,但变量名并不合并这些值,因此我将每个变量都作为一个新的值名.
此外,我必须指定转换中的所有值名称,这很繁琐,因为现在有40多个变量.
import pandas as pd
# create a dataframe with an x, x.1, and y, y.2 column
df = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'x.1': [1, 2, 3, 4, 5], 'y': [1, 2, 3, 4, 5], 'y.1': [1, 2, 3, 4, 5],})
# add an id column
df['id'] = df.index
# change from wide to long format using melt
df = pd.melt(df, id_vars=['id'], value_vars=['x', 'x.1', 'y', 'y.1'], var_name='variable', value_name='value')
print(df)
我是从哪里得到这个输出的
id variable value
0 0 x 1
1 1 x 2
2 2 x 3
3 3 x 4
4 4 x 5
5 0 x.1 1
6 1 x.1 2
7 2 x.1 3
8 3 x.1 4
9 4 x.1 5
10 0 y 1
11 1 y 2
12 2 y 3
13 3 y 4
14 4 y 5
15 0 y.1 1
16 1 y.1 2
17 2 y.1 3
18 3 y.1 4
19 4 y.1 5
但我想要的是收集这样的价值观:
id variable value
0 0 x 1
1 1 x 2
2 2 x 3
3 3 x 4
4 4 x 5
5 0 x 1
6 1 x 2
7 2 x 3
8 3 x 4
9 4 x 5
10 0 y 1
11 1 y 2
12 2 y 3
13 3 y 4
14 4 y 5
15 0 y 1
16 1 y 2
17 2 y 3
18 3 y 4
19 4 y 5
我怎么能这样做呢?理想的方式是,当我融化数据帧时,我不需要有一个超长的列表