Pandas - Column Sort

I have a pandas data frame known as "df":

  x y
0 1 2
1 2 4
2 3 8

I split it into two frames, and then try to combine them together:

df_1 = df[df['x']==1]  
df_2 = df[df['x']!=1] 

My goal is to return it in the same order, but when I agree, I get the following:

frames = [df_1, df_2]
solution = pd.concat(frames)
solution.sort_values(by='x', inplace=False)

  x y
1 2 4
2 3 8
0 1 2

The problem is that I need the "x" values ​​to return to the new data framework in the same order that I extracted. Is there a solution?

+4
source share
4 answers

use .locto indicate the desired order. Select the source index.

solution.loc[df.index]

Or, if you trust the index values ​​in each component, then

solution.sort_index()

enter image description here

customization

df = pd.DataFrame([[1, 2], [2, 4], [3, 8]], columns=['x', 'y'])

df_1 = df[df['x']==1]  
df_2 = df[df['x']!=1] 

frames = [df_1, df_2]
solution = pd.concat(frames)
+3
source

Try the following:

In [14]: pd.concat([df_1, df_2.sort_values('y')])
Out[14]:
   x  y
0  1  2
1  2  4
2  3  8
0
source

, solution.sort_values(by='x', inplace=False) inplace = True. .

0

df:

  • Columns xand ymarked are required.
  • The index is ordered.

Just order your result by index:

df = pd.DataFrame({'x': [1, 2, 3], 'y': [2, 4, 8]})
df_1 = df[df['x']==1]  
df_2 = df[df['x']!=1] 
frames = [df_2, df_1]
solution = pd.concat(frames).sort_index()

Now solutionit looks like this:

   x  y
0  1  2
1  2  4
2  3  8
0
source

Source: https://habr.com/ru/post/1664010/


All Articles