python - Display Pandas DataFrame in csv format -
i have pandas dataframe q2
looks this:
studentid subjects 6 323 history 9 323 physics 8 999 chemistry 7 999 history 4 999 physics 0 1234 chemistry 5 2834 physics 1 3455 chemistry 2 3455 history 10 3455 mathematics 3 56767 mathematics
i want find out student has taken courses , display on screen.
gb = q2.groupby(('studentid')) result = gb['subjects'].unique() c1=pd.dataframe({'studentid':result.index, 'subjects':result.values})
c1
looks this
studentid subjects 0 323 [history, physics] 1 999 [chemistry, history, physics] 2 1234 [chemistry] 3 2834 [physics] 4 3455 [chemistry, history, mathematics] 5 56767 [mathematics]
however, desired output following:
323: history, physics 999: chemistry, history, physics 1234: chemistry 2834: physics 3455: chemistry, history, mathematics 56767: mathematics
what can do?
i think can apply
function join
. creating dataframe
can use reset_index
:
gb = q2.groupby(('studentid')) result = gb['subjects'].unique() c1 = result.reset_index() c1.subjects = c1.subjects.apply(', '.join) print (c1) studentid subjects 0 323 history, physics 1 999 chemistry, history, physics 2 1234 chemistry 3 2834 physics 4 3455 chemistry, history, mathematics 5 56767 mathematics
last can cast column studentid
str
(if dtype
int
) , concanecate together:
c1['new'] = c1.studentid.astype(str) + ':' + c1.subjects print (c1) studentid subjects \ 0 323 history, physics 1 999 chemistry, history, physics 2 1234 chemistry 3 2834 physics 4 3455 chemistry, history, mathematics 5 56767 mathematics new 0 323:history, physics 1 999:chemistry, history, physics 2 1234:chemistry 3 2834:physics 4 3455:chemistry, history, mathematics 5 56767:mathematics
also if original data can overwrite, use:
result = result.index.to_series().astype(str) + ':' + result.apply(', '.join) print (result) studentid 323 323:history, physics 999 999:chemistry, history, physics 1234 1234:chemistry 2834 2834:physics 3455 3455:chemistry, history, mathematics 56767 56767:mathematics dtype: object
Comments
Post a Comment