Write a program in Python to perform flatten the records in a given dataframe by C and F order

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for flatten records in C and F order as,

flat c_order:
   [10 12 25 13 3 12 11 14 24 15 6 14]
flat F_order:
   [10 25 3 11 24 6 12 13 12 14 15 14]

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Apply df.values.ravel() function inside set an argument as order=’C’ and save it as C_order,

C_order = df.values.ravel(order='C')
  • Apply df.values.ravel() function inside set an argument as order=’F’ and save it as F_order,

F_order = df.values.ravel(order='F')

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[10, 25, 3, 11, 24, 6],
                     'Age':[12,13,12,14,15,14] })
print("Dataframe is:\n",df)
C_order = df.values.ravel(order='C')
print("flat c_order:\n",C_order)
F_order = df.values.ravel(order='F')
print("flat F_order:\n",F_order)

Output

Dataframe is:
  Id Age
0 10 12
1 25 13
2  3 12
3 11 14
4 24 15
5  6 14
flat c_order:
   [10 12 25 13 3 12 11 14 24 15 6 14]
flat F_order:
   [10 25 3 11 24 6 12 13 12 14 15 14]
raja
Published on 12-Feb-2021 10:35:45
Advertisements