2015-07-09 14 views
6

Per esempio, ho dataframe ora comeCome convertire file in dataframe in Python per dizionari

id score1 score2 score3 score4 score5 
1 0.000000  0.108659 0.000000 0.078597 1 
2 0.053238  0.308253 0.286353 0.446433 1 
3 0.000000  0.083979 0.808983 0.233052 1 

voglio convertirlo come

id scoreDict 
1 {'1': 0, '2': 0.1086, ...} 
2 {...} 
3 {...} 

Comunque per farlo?

Grazie in anticipo!

+0

Si prega di considerare di accettare una delle varie risposte alle tue domande precedenti in quanto questo è il galateo su SO se le risposte hanno risposto alla tua domanda, ci sarà un segno di spunta vuota segnare in alto a sinistra delle risposte – EdChum

risposta

22
import pandas as pd 

# your df 
# ========================= 
print(df) 

    id score1 score2 score3 score4 score5 
0 1 0.0000 0.1087 0.0000 0.0786  1 
1 2 0.0532 0.3083 0.2864 0.4464  1 
2 3 0.0000 0.0840 0.8090 0.2331  1 

# to_dict 
# ========================= 
df.to_dict(orient='records') 

Out[318]: 
[{'id': 1.0, 
    'score1': 0.0, 
    'score2': 0.10865899999999999, 
    'score3': 0.0, 
    'score4': 0.078597, 
    'score5': 1.0}, 
{'id': 2.0, 
    'score1': 0.053238000000000001, 
    'score2': 0.308253, 
    'score3': 0.28635300000000002, 
    'score4': 0.44643299999999997, 
    'score5': 1.0}, 
{'id': 3.0, 
    'score1': 0.0, 
    'score2': 0.083978999999999998, 
    'score3': 0.80898300000000001, 
    'score4': 0.23305200000000001, 
    'score5': 1.0}] 
1

Penso che il codice seguente ti fornisca il frame di dati nel formato che stai cercando. Inoltre, consente di scegliere qualsiasi colonna come un indice

import pandas as pd 

#IMPORT YOUR DATA 
#Any other way to import data can also be used. I saved it in .csv file 
df=pd.read_csv('dftestid.csv') 
print("INITIAL DATAFRAME") 
print(df) 
print() 

#Convert Data Frame to Dictionary (set_index method allows any column to be used as index) 
df2dict=df.set_index('id').transpose().to_dict(orient='dict') 


#Convert Dictionary to List with 'score' replaced 
dicttolist=[[k,{int(k1.replace('score','')):v1 for k1,v1 in v.items()}] for k,v in df2dict.items()] 

#"Create the new DataFrame" 

df2=pd.DataFrame(dicttolist,columns=['id', 'scoreDict']) 
print("NEW DATAFRAME") 
print(df2) 


OUT: 
INITIAL DATAFRAME 
    id score1 score2 score3 score4 score5 
0 1 0.000000 0.108659 0.000000 0.078597  1 
1 2 0.053238 0.308253 0.286353 0.446433  1 
2 3 0.000000 0.083979 0.808983 0.233052  1 

NEW DATAFRAME 
    id           scoreDict 
0 1 {1: 0.0, 2: 0.108659, 3: 0.0, 4: 0.078597, 5: ... 
1 2 {1: 0.053238, 2: 0.308253, 3: 0.286353, 4: 0.4... 
2 3 {1: 0.0, 2: 0.083979, 3: 0.808983, 4: 0.233052... 
Problemi correlati