Perform a "Text-To-Columns' in a Panda's DF and copy existing row into a new row

huangapple go评论127阅读模式
英文:

Perform a "Text-To-Columns' in a Panda's DF and copy existing row into a new row

问题

我有一个包含特定列值的数据框,我想将其拆分并复制到新的行中。例如:

Order#              Price             Quantity
123                   $20                5
456,789               $50                7
321                   $45                3
121,651               $76                9

在"Order#"列中的某些行包含由逗号分隔的两个订单号。我希望每个订单号都有自己的行。例如,我希望将第二行(456, 789)通过逗号分隔符拆分为两行。最终结果应该如下所示:

Order#              Price             Quantity
123                   $20                5
456                   $50                7
789                   $50                7
321                   $45                3
121                   $76                9
651                   $76                9

我尝试了以下代码:

df['Order Column'].str.split(",", expand=True)

但是卡住了。感谢任何帮助。

英文:

I have a df with certain column values that I want to split and then copy into new rows. For example:


Order#              Price             Quantity
123                   $20                5
456,789               $50                7
321                   $45                3
121,651               $76                9

Some rows in the "order#" column contain two order numbers separated by a column. I want each order# to have its own row. For example, I want the second row (456, 789) to be split by the column delimeter into two rows. The final result would look like:

Order#              Price             Quantity
123                   $20                5
456                   $50                7
789                   $50                7
321                   $45                3
121                   $76                9
651                   $76                9

I tried doing something like:

df['Order Column'].str.split(",", expand=True)   

but then got stuck.
Appreciate any input.

答案1

得分: 0

你需要在split之后使用explode函数:

df["Order#"] = df["Order#"].str.split(",")
df.explode("Order#")

这样可以将Order#列中的每个元素拆分成多行,并复制其他列的值。

英文:

You need to explode after split:

df["Order#"] = df["Order#"].str.split(",")

>>> df.explode("Order#")
  Order# Price  Quantity
0    123   $20         5
1    456   $50         7
1    789   $50         7
2    321   $45         3
3    121   $76         9
3    651   $76         9

huangapple
  • 本文由 发表于 2023年8月8日 23:56:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861273.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定