2017-09-21 62 views
0

我的問題一欄是類似這樣的:解開包含元素的列表作爲字符串

pandas: When cell contents are lists, create a row for each element in the list

我想在樣品列表中的每個元素創建重複的行,但現在的元素存儲爲一個字符串,是這樣的:

    samples subject trial_num 
0 '[string1, string21, string3]'  1   1 
1 '[string3, string24, string3]'  1   2 
2 '[string4, string24, string4]'  1   3 
3 '[string5, string24, string5]'  2   1 
4 '[string13, string24, string6]'  2   2 
5 '[string16, string24, string6]'  2   3 

謝謝

回答

0
from ast import literal_eval 

df.assign(samples=df.samples.str.strip("'").apply(literal_eval)).pipe(
    lambda d: d.loc[d.index.repeat(d.samples.str.len())].assign(
     samples=np.concatenate(d.samples) 
    ) 
) 

    samples subject trial_num 
0  0.57  1   1 
0 -0.83  1   1 
0  1.44  1   1 
1 -0.01  1   2 
1  1.13  1   2 
1  0.36  1   2 
2  1.18  1   3 
2 -1.46  1   3 
2 -0.94  1   3 
3 -0.08  2   1 
3 -4.22  2   1 
3 -2.05  2   1 
4  0.72  2   2 
4  0.79  2   2 
4  0.53  2   2 
5  0.40  2   3 
5 -0.32  2   3 
5 -0.13  2   3 
+0

我剛剛編輯了將字符串放入樣本列(這是我的情況)中的問題。用你的解決方案,我有一個錯誤「格式錯誤的字符串」 – user3620915

相關問題