簡體   English   中英

使用相同的Id,pandas從多個列表創建多個行

[英]creating multiple rows from multiple list using same Id, pandas

我有一個像這樣的示例數據框,Column: IDMain

ID,Main
0,[30 115 266 38;662 99 1199 43] [511 133 25 47] [664 162 49 22]

如何使用pandas使我的數據幀如下所示

預期產出

ID,Main
0,30 115 266 38
0,662 99 1199 43
0,511 133 25 47
0,664 162 49 22

首先replace ; by ][然后通過findallSeries list s提取[]之間的值。

最后創建DataFrame ,通過stack重新DataFrame ,並通過reset_index清除一些數據:

s = df['Main'].fillna('').str.replace(';','][').str.findall('\[(.*?)\]')
df = (pd.DataFrame(s.values.tolist(), index=s.index)
        .stack()
        .reset_index(level=1, drop=True)
        .reset_index())
df.columns = ['ID','Main']
print (df)
   ID            Main
0   0   30 115 266 38
1   0  662 99 1199 43
2   0   511 133 25 47
3   0   664 162 49 22

Series另一個解決方案

s = df['Main'].fillna('').str.strip('[]').str.split(';|\]\s+\[')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM