[英]creating multiple rows from multiple list using same Id, pandas
我有一個像這樣的示例數據框,Column: ID
和Main
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 ][
然后通過findall
為Series
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.