Reputation: 13
Python Beginner question: I have a dataframe with a X x Y shape. I want to convert it to a 1 x (X*Y) header file. So for example as below a 4x4 pandas df:
a e i m
b f j n
c g k o
d h l p
I want the output to be 1x16 (a,b,c,d,e,f...o,p). This has to be a COLUMN not row entry. Is dataframe manipulation the best way or should I use numpy? I am starting from an xls file of X x Y.
My code:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import numpy.random as nr
import math
%matplotlib inline
#Load Data & Quick Peak
hdr = pd.read_excel('header.xls', header=None)
print(hdr)
hdr.shape
Upvotes: 0
Views: 201
Reputation: 2472
Reshaping the transpose of your dataframe 'hdr' according to choice may help. For example,
hdr = pd.read_excel('header.xls', header = None)
hdr_arr = df.T.values.reshape(1,16)
This converts the dataframe to an array of 1x16.
Upvotes: 0
Reputation: 478
You can simply use melt()
like so:
import pandas as pd
data = {'col1': ['a', 'b', 'c', 'd'],
'col2': ['e', 'f', 'g', 'h'],
'col3': ['i', 'j', 'k', 'l'],
'col4': ['m', 'n', 'o', 'p']}
df = pd.DataFrame(data)
print(df.melt()['value'])
result:
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
11 l
12 m
13 n
14 o
15 p
Upvotes: 1