How to create a data frame in python using pandas ?

Daidalos October 15, 2019


Examples of how to create a data frame using the python module pandas

Create a data frame using an array

Import pandas and numpy:

>>> import pandas as pd
>>> import numpy as np

Let's consider the following matrix

\begin{equation}
data = \left( \begin{array}{ccc}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8 \\
9 & 10 & 11 & 12
\end{array}\right)
\end{equation}

>>> data = np.arange(1,13)
>>> data = data.reshape(3,4)
>>> data
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Give names to columns

>>> columns = ['Home','Car','Sport','Food']

Give names to rows

>>> index = ['Alice','Bob','Emma']

Create a data frame using pandas:

>>> df = pd.DataFrame(data=data,index=index,columns=columns)
>>> df
       Home  Car  Sport  Food
Alice     1    2      3     4
Bob       5    6      7     8
Emma      9   10     11    12

An example without the index

>>> df = pd.DataFrame(data=data,columns=columns)
>>> df
   Home  Car  Sport  Food
0     1    2      3     4
1     5    6      7     8
2     9   10     11    12

Create a data frame using a dictionary

Example using a dictionary

>>> data = {'Food':[4,8,12],'Car':[1,5,9],'Home':[2,6,10]}
>>> df = pd.DataFrame(data=data)
>>> df
   Car  Food  Home
0    1     4     2
1    5     8     6
2    9    12    10

another example:

>>> data = {'Home':{'Alice':1,'Bob':5,'Emma':9},'Car':{'Alice':2,'Bob':6,'Emma':10}}
>>> df = pd.DataFrame(data=data)
>>> df
       Car  Home
Alice    2     1
Bob      6     5
Emma    10     9

Create a data frame using a list of tuple

Example using a list of tuple

>>> data = [(1,2,3,4),(5,6,7,8)]
>>> index = ['Alice','Bob']
>>> columns = ['Home','Car','Sport','Food']
>>> df = pd.DataFrame(data=data,index=index,columns=columns)
>>> df
       Home  Car  Sport  Food
Alice     1    2      3     4
Bob       5    6      7     8

Create a data frame from a ascii file

To extract data from a file and create a data frame a solution is to use read_csv()

>>> import pandas as pd
>>> df = pd.read_csv('myfile.csv', sep=",", header=None)
>>> df.head()

References

Links Site
Different ways to create Pandas Dataframe geeksforgeeks
pandas.DataFrame pandas.pydata.org
How to Create Pandas DataFrame in Python datatofish
Create Pandas DataFrame from txt file with specific pattern stackoverflow
Create Pandas DataFrame from txt file with specific pattern stackoverflow
How to store a dataframe using Pandas stackoverflow
intro to data structures pandas doc

Licence


Activity


Google Ads