簡體   English   中英

Pandas:將非數字標識符代碼拆分為多行

[英]Pandas: Splitting a non-numeric identifier code into multiple rows

假設我有一個看起來像這樣的數據集

Unique_Identifier  Score1 Score2
112                   50     60 
113-114               50     70 
115                   40     20 
116-117               30     90 
118                   70     70 

請注意我的一些唯一標識符是如何列為范圍而不是精確值的。 我想將這些范圍拆分為 2 個具有相同分數的單獨行,以便它看起來像這樣:

Unique_Identifier  Score1 Score2
112                   50     60 
113                   50     70
114                   50     70
115                   40     20 
116                   30     90
117                   30     90 
118                   70     70 

我 go 如何使用 Pandas 在 Python 中執行此操作? 我認為可能有一種方法可以測試其中包含“-”的行,但我不確定 go 如何拆分這些行。 我還應該注意,某些標識符范圍中的標識符不止 2 個,例如 120-124。

df.assign(Unique_Identifier=df.Unique_Identifier.str.split('-')).explode('Unique_Identifier')

  Unique_Identifier  Score1  Score2
0               112      50      60
1               113      50      70
1               114      50      70
2               115      40      20
3               116      30      90
3               117      30      90
4               118      70      70

split為“-”並創建具有所需range的列表。 然后explode成單獨的行:

df["Unique_Identifier"] = df["Unique_Identifier"].apply(lambda x: list(range(int(x.split("-")[0]),int(x.split("-")[1])+1)) if "-" in x else [int(x)])
df = df.explode("Unique_Identifier")

>>> df
  Unique_Identifier  Score1  Score2
0               112      50      60
1               113      50      70
1               114      50      70
2               115      40      20
3               116      30      90
3               117      30      90
4               118      70      70
5               120      80      80
5               121      80      80
5               122      80      80
5               123      80      80
5               124      80      80

暫無
暫無

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

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