2015-04-12 65 views

回答

4

假設你的起始數據框被命名爲df,你可以寫:

>>> df2 = df.asn.str.split(',').apply(pd.Series)   # break df.asn into columns 
>>> df2.index = df.Name         # set the index as df.Name 
>>> df2 = df2.stack().reset_index('Name')     # stack and reset_index 
>>> df2 
    Name  0 
0 Org1 asn1 
1 Org1 asn2 
0 org2 asn3 
0 org3 asn4 
1 org3 asn5 

所有剩下要做的就是重新命名列:

df2.rename(columns={0: 'asn'}, inplace=True) 

根據你的下一步行動,你可能還需要設置更有用的索引。

+0

不錯。你也可以使用'reset_index('Name')'來避免'drop'('level_1',axis = 1)'。 – unutbu

+0

感謝@unutbu,看起來很整潔。 –

+0

@ ajcr.Thanks。 ONe問題,如果我有三列?第三列,我喜歡像'名字'欄 – UserYmY

相關問題