2017-08-01 124 views
1

我無法拆分包含分號的熊貓系列。是因爲我使用列名('Social_Media')作爲索引,還是因爲python不會識別分號作爲分隔符?或者我的腳本有問題?熊貓將包含字符串的分隔列分隔爲多列

#Filters the NaN columns 
df2 = df[df['Social_Media'].notnull()] 
# Splitter for semicolon 
df2['Social_Media'].apply(lambda x: x.split(';')[0]) 

#This is my output after the split 
Timestamp        
2017-06-01 18:10:46   Twitter;Facebook;Instagram;WhatsApp;Google+ 
2017-06-01 19:24:04   Twitter;Facebook;Instagram;WhatsApp;Google+ 
2017-06-01 19:25:21   Twitter;Facebook;Instagram;WhatsApp;Google+ 

我需要看到的輸出。

Timestamp     name_a name_b name_c name_d name_e 
2017-06-01 18:10:46   Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:24:04   Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:25:21   Twitter Facebook Instagram WhatsApp Google+ 
+1

非常感謝,這真是棒極了。還要感謝關於如何處理字符串的附加建議 – Gwiji

回答

0

您可以通過字母使用str.split

df = df['Social_Media'].str.split(';', expand=True).add_prefix('name_') 
print (df) 
         name_0 name_1  name_2 name_3 name_4 
Timestamp               
2017-06-01 18:10:46 Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:24:04 Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:25:21 Twitter Facebook Instagram WhatsApp Google+ 

而對於列名:

import string 
L = list(string.ascii_lowercase) 
names = dict(zip(range(len(L)), ['name_' + x for x in L])) 

df = df['Social_Media'].str.split(';', expand=True).rename(columns=names) 
print (df) 
         name_a name_b  name_c name_d name_e 
Timestamp               
2017-06-01 18:10:46 Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:24:04 Twitter Facebook Instagram WhatsApp Google+ 
2017-06-01 19:25:21 Twitter Facebook Instagram WhatsApp Google+