我需要通过选择多个列,并将这些列值附加到新列,并将其相应的索引作为新列,从现有数据帧创建一个新数据框
所以,假设我将其作为数据框:
A B C D E F
0 1 2 3 4 0
0 7 8 9 1 0
0 4 5 2 4 0
通过选择 B 列到 E 列来转换为此形式:
A index_value
1 1
7 1
4 1
2 2
8 2
5 2
3 3
9 3
2 3
4 4
1 4
4 4
因此,对于新数据帧,A
列将是旧数据帧中 B 至 E
列的所有值,index_value
列code> 将对应于所选列的索引值[从零开始]。
我已经挠头好几个小时了。任何帮助将不胜感激,谢谢!
Python3,使用 pandas 和 numpy 库。
最佳答案
#Another way
A B C D E F
0 0 1 2 3 4 0
1 0 7 8 9 1 0
2 0 4 5 2 4 0
# Select columns to include
start_colum ='B'
end_column ='E'
index_column_name ='A'
#re-stack the dataframe
df = df.loc[:,start_colum:end_column].stack().sort_index(level=1).reset_index(level=0, drop=True).to_frame()
#Create the "index_value" column
df['index_value'] =pd.Categorical(df.index).codes+1
df.rename(columns={0:index_column_name}, inplace=True)
df.set_index(index_column_name, inplace=True)
df
index_value
A
1 1
7 1
4 1
2 2
8 2
5 2
3 3
9 3
2 3
4 4
1 4
4 4
关于python - 使用 pandas 将新数据帧索引到新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57086287/