Home  >  Article  >  Backend Development  >  How to Combine Two DataFrames with Differing Indexes While Maintaining Original Order and Indexes?

How to Combine Two DataFrames with Differing Indexes While Maintaining Original Order and Indexes?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 06:52:29676browse

How to Combine Two DataFrames with Differing Indexes While Maintaining Original Order and Indexes?

Combining Two DataFrames with Differing Indexes

You have a dataframe D and have extracted two dataframes A and B from it:

<code class="python">A = D[D.label == k]
B = D[D.label != k]</code>

Your goal is to combine A and B into a single DataFrame, preserving the original order of data from D while retaining the indexes from D.

Solution via Deprecated Method

While DataFrame.append and Series.append are deprecated in v1.4.0, they can still be used for this task with the argument ignore_index set to True. This will discard the original indexes and reindex the combined dataframe from 0 to n-1.

<code class="python">df_merged = df1.append(df2, ignore_index=True)</code>

Solution with Preserved Indexes

If you want to retain the original indexes, set ignore_index to False. This will append the dataframes vertically and retain their respective indexes.

<code class="python">df_merged = df1.append(df2, ignore_index=False)</code>

The above is the detailed content of How to Combine Two DataFrames with Differing Indexes While Maintaining Original Order and Indexes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn