英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论