Home > Article > Backend Development > Here are some question-style titles based on the information provided: Clear and Concise: * How to Split Comma-Separated Values into Multiple Rows in a Pandas DataFrame? * Splitting Columns with Com
Split Cells into Multiple Rows in pandas DataFrame
Question:
How can I split comma-separated [package and package_code] columns into multiple rows in a pandas DataFrame, creating a new row for each package with its corresponding order details?
Answer:
Method 1: (pandas >= 0.25)
<code class="python">df.set_index(['order_id', 'order_date']) \ .apply(lambda x: x.str.split(',').explode()) \ .reset_index() </code>
Method 2: (pandas <= 0.24)
<code class="python">(df.set_index(['order_date', 'order_id']) .stack() .str.split(',', expand=True) .stack() .unstack(-2) .reset_index(-1, drop=True) .reset_index() )</code>
Details:
The above is the detailed content of Here are some question-style titles based on the information provided: Clear and Concise: * How to Split Comma-Separated Values into Multiple Rows in a Pandas DataFrame? * Splitting Columns with Com. For more information, please follow other related articles on the PHP Chinese website!