Python 从多列获取数据帧标签索引
我正在研究如何根据列值获取Python 从多列获取数据帧标签索引,python,pandas,dataframe,Python,Pandas,Dataframe,我正在研究如何根据列值获取DataFrame中标签的索引。我有以下数据帧: d = {'col1': ['label1', 'label2', 'label3'], 'col2': ['label2', 'label3', 'label1'], 'col3': ['label2', 'label1', 'label3'], 'col4': ['label3', 'label1', 'label2']} df = pd.DataFrame(data = d)
DataFrame
中标签的索引。我有以下数据帧
:
d = {'col1': ['label1', 'label2', 'label3'],
'col2': ['label2', 'label3', 'label1'],
'col3': ['label2', 'label1', 'label3'],
'col4': ['label3', 'label1', 'label2']}
df = pd.DataFrame(data = d)
哪些格式为:
col1 col2 col3 col4
0 label1 label2 label2 label3
1 label2 label3 label1 label1
2 label3 label1 label3 label2
我正在尝试将其转换为以下形式:
label1 label2 label3
col1 0 1 2
col2 2 0 1
col3 1 0 2
col4 1 2 0
这说明了原始数据帧df
中相应列中每个标签的索引。例如,在col3
中,标签1-3的索引分别为1、0和2。与and一起使用:
或与及:
最后一步是删除索引和列名:
df1.index.name = None
df1.columns.name = None
print (df1)
label1 label2 label3
col1 0 1 2
col2 2 0 1
col3 1 0 2
col4 1 2 0
您可以然后:
df1 = df.reset_index().melt('index').pivot('variable','value','index')
print (df1)
value label1 label2 label3
variable
col1 0 1 2
col2 2 0 1
col3 1 0 2
col4 1 2 0
df1.index.name = None
df1.columns.name = None
print (df1)
label1 label2 label3
col1 0 1 2
col2 2 0 1
col3 1 0 2
col4 1 2 0
res = pd.DataFrame(df.T.values.argsort(1),
columns=np.sort(df.iloc[:, 0].values),
index=df.columns)
print(res)
label1 label2 label3
col1 0 1 2
col2 2 0 1
col3 1 0 2
col4 1 2 0