2016-09-15 43 views
2

我從CSV中讀取的數據中有一個熊貓數據框。一列是一組的名稱,而另一列包含一個字符串(看起來像一個列表),如下所示:在熊貓數據框中取出一串字符串數據並分割成單獨的列

Group  | Followers 
------------------------------------------ 
biebers | u'user1', u'user2', u'user3' 
catladies | u'user4', u'user5' 
bkworms | u'user6', u'user7' 

我想嘗試拆分字符串中的「關注」欄目,讓一個單獨的數據幀,每一行是用戶,還有一欄顯示他們所處哪個組因此,對於這個例子,我想獲得如下:

User  |  Group 
-------------------------------- 
user1  |  biebers 
user2  |  biebers 
user3  |  biebers 
user4  |  catladies 
user5  |  catladies 
user6  |  bkworms 
user7  |  bkworms 

任何人有最好的方法來解決這個問題的建議?這裏是什麼樣子的截圖:

enter image description here

+0

你是什麼意思「看起來像列表的字符串?」它看起來像多個unicode字符串的列表嗎?那到底是怎麼回事? –

+0

是的條目都是字符串(這看起來像一個unicode字符串列表)。數據是從CSV中讀取的,它返回所有條目的字符串... – Imu

+0

可以發佈df.head(10) –

回答

2
df.Followers = df.Followers.str.replace(r"u'([^']*)'", r'\1') 

df.set_index('Group').Followers.str.split(r',\s*', expand=True) \ 
    .stack().rename('User').reset_index('Group').set_index('User') 

enter image description here


爲了保持User爲一列。

df.Followers = df.Followers.str.replace(r"u'([^']*)'", r'\1') 

df.set_index('Group').Followers.str.split(r',\s*', expand=True) \ 
    .stack().rename('User').reset_index('Group') \ 
    .reset_index(drop=True)[['User', 'Group']] 
+0

哦,哇,永遠不會知道'expand = True',它會派上用場。 –

+0

太棒了!我想知道如何使df這樣的用戶不是索引,但只是另一列...對不起,我不清楚我需要的確切輸出... – Imu

+0

@Imu容易,這是一個選擇我的。我會更新我的帖子。 – piRSquared

相關問題