Will passing ignore_index=True to pd.concat preserve index succession within dataframes that I'm concatenating?

╄→尐↘猪︶ㄣ 提交于 2021-02-07 12:05:49

问题


I have two dataframes:

df1 = 
    value
0     a
1     b
2     c

df2 =
    value
0     d
1     e

I need to concatenate them across index, but I have to preserve the index of the first dataframe and continue it in the second dataframe, like this:

result =
    value
0     a
1     b
2     c
3     d
4     e

My guess is that pd.concat([df1, df2], ignore_index=True) will do the job. However, I'm worried that for large dataframes the order of the rows may be changed and I'll end up with something like this (first two rows changed indices):

result =
    value
0     b
1     a
2     c
3     d
4     e

So my question is, does the pd.concat with ignore_index=True save the index succession within dataframes that are being concatenated, or there is randomness in the index assignment?


回答1:


In my experience, pd.concat concats the rows in the order the DataFrames are passed to it during concatenation.


If you want to be safe, specify sort=False which will also avoid sorting on columns:

pd.concat([df1, df2], axis=0, sort=False, ignore_index=True)

  value
0     a
1     b
2     c
3     d
4     e


来源:https://stackoverflow.com/questions/56546312/will-passing-ignore-index-true-to-pd-concat-preserve-index-succession-within-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!