Reshaping 4×1 DataFrame into 2×2 DataFrame
Question:
I have a DataFrame as below:
import pandas as pd
df_testcase = pd.DataFrame(
['16SCSE102014', '15/03/2019', '16SCSE101350', '15/03/2019']
)
0
0 16SCSE102014
1 15/03/2019
2 16SCSE101350
3 15/03/2019
I need to convert it into 2×2 DataFrame like this:
0 1
0 16SCSE102014 15/03/2019
1 16SCSE101350 15/03/2019
Can someone please help?
Answers:
I’m not sure whether there is a trivial way to do that using pandas dataframe. But you can do it using numpy as such:
import pandas as pd
import numpy as np
df = pd.DataFrame({'the_only_column':[1,'a',2,'b',3,'c']})
np_array = np.array(df['the_only_column'])
np_array = np.reshape(np_array, (np_array.shape[0]//2, 2))
df = pd.DataFrame(np_array, columns=['new_column_name', 'other_column_name'])
print(df)
And the output is:
new_column_name other_column_name
0 1 a
1 2 b
2 3 c
I have a DataFrame as below:
import pandas as pd
df_testcase = pd.DataFrame(
['16SCSE102014', '15/03/2019', '16SCSE101350', '15/03/2019']
)
0
0 16SCSE102014
1 15/03/2019
2 16SCSE101350
3 15/03/2019
I need to convert it into 2×2 DataFrame like this:
0 1
0 16SCSE102014 15/03/2019
1 16SCSE101350 15/03/2019
Can someone please help?
I’m not sure whether there is a trivial way to do that using pandas dataframe. But you can do it using numpy as such:
import pandas as pd
import numpy as np
df = pd.DataFrame({'the_only_column':[1,'a',2,'b',3,'c']})
np_array = np.array(df['the_only_column'])
np_array = np.reshape(np_array, (np_array.shape[0]//2, 2))
df = pd.DataFrame(np_array, columns=['new_column_name', 'other_column_name'])
print(df)
And the output is:
new_column_name other_column_name
0 1 a
1 2 b
2 3 c