In Pandas, the order of variables changes unexpectedly after adding Series to the empty DataFrame?

the reason has been found. The order of variables from append to the data box will be adjusted automatically when the column tag of DataFrame is not set beforehand.

df = pd.DataFrame()
series=pd.Series([3,4,1,6],index=["b","a","d","c"])
df=df.append(series,ignore_index=True)

the output of the above code is:

     a    b    c    d
0  4.0  3.0  6.0  1.0

if you want to overcome this problem, except

df = pd.DataFrame(columns=series.index)

I don"t know what else to do.

Jun.22,2022

does not understand the code logic. If you want to maintain the order of series, you can directly assign values to the new dataframe column, such as

.
s1 = Series([1,2,3])
s2 = Series(['a','b','c'])
df = DataFrame()
df['1'] = s1
df['2'] = s2
Menu