python - 使用 pandas 将新数据帧索引到新列中

标签 python python-3.x pandas numpy

我需要通过选择多个列,并将这些列值附加到新列,并将其相应的索引作为新列,从现有数据帧创建一个新数据框

所以,假设我将其作为数据框:

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/

相关文章:

python - 在 PyDev 编辑器中换行文本

python - 如何从带有子元组的元组创建列表?

python - 如何从 CSV 文件子集创建自定义 DataFrame

python - 如何将 Keras 模型摘要写入数据框?

python - SearchFieldError Django 和 Haystack

javascript - javascript日期对象与python日期时间对象兼容吗

python 3 : Why does __spec__ work?

python - 数据操作 - 当值为字母数字时排序索引

python - 不会将本地文件作为模块导入

Python 文件() 函数