2015-04-12 60 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

相关问题