# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/programres1/DataFrame/blob/main/001/Different_ways_to_create_DataFrame.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="30QQ5Uap62IV"
# #Different ways to create DataFrame
#

# + id="nbSzxZFc7EnE"
# Import pandas library
import pandas as pd
import numpy as np

# + [markdown] id="qKlLHBkj8SOF"
# **Method 1: From list of lists**

# + colab={"base_uri": "https://localhost:8080/", "height": 213} id="aPxrrI5a7Ii0" outputId="f8c2e839-441c-41c0-c968-e75fbdd102dc"
# list of lists
data = [['ram', 10], ['raju', 11], ['rajesh', 14]]
 
# pass column names as list in columns parameter 
df = pd.DataFrame(data, columns = ['Name', 'Age']) 
 
print(df)

df = pd.DataFrame(data)
df

# + [markdown] id="2Wx-4R5M8_vw"
# **Method 2: From 2-D narray**

# + colab={"base_uri": "https://localhost:8080/", "height": 175} id="G0cNOodE8bhk" outputId="d97c897a-2f97-4242-829b-a7c9b81f54ee"
#np array
data = np.array([[2014,"toyota","corolla"], 
                 [2018,"honda","civic"], 
                 [2020,"hyndai","accent"], 
                 [2017,"nissan","sentra"]]) 


df = pd.DataFrame(data, columns = ['year', 'make','model'])
df

# + [markdown] id="SmQ36f6p9dxt"
# **Method 3: From dict of narray/lists**

# + colab={"base_uri": "https://localhost:8080/", "height": 175} id="MMZqOR1Y9kwk" outputId="830022b7-d036-4f12-958a-b654018d085f"
data = {
    'Name':['Tom', 'nick', 'krish', 'jack'],
        'Age':[20, 21, 19, 18]
        }

#Dictionary Keys become Column names in the dataframe 
# pass index names as list in index parameter 
df = pd.DataFrame(data,index =['rank1',
                                'rank2',
                                'rank3',
                                'rank4'])
 

print(df)


data = {
    'Name':np.array(['Tom', 'nick', 'krish', 'jack']),
        'Age':[20, 21, 19, 18]
        }
 

df = pd.DataFrame(data,index =['rank1',
                                'rank2',
                                'rank3',
                                'rank4'])
 

df

# + [markdown] id="AjzjejuK-hcV"
# **Method 4:Using from_dict method**
#
# Using from_dict, we have the ability to chose any column as an index of the dataframe(Difference from Method-3).orient='index' makes it possible.
# It creates data frames as transpose, in creation phase itself.

# + colab={"base_uri": "https://localhost:8080/", "height": 230} id="DFIpzTNR_OOt" outputId="409851a5-835a-4109-c515-d866402ed304"
data = {'year': [2014, 2018,2020,2017], 
        'make': ["toyota", "honda","hyndai","nissan"],
        'model':["corolla", "civic","accent","sentra"]
       }

df = pd.DataFrame.from_dict(data)
print(df)

df = pd.DataFrame.from_dict(data,orient='index')
df  

# + [markdown] id="TIITqnDx_N6y"
# **Method 5: From list of dicts**

# + colab={"base_uri": "https://localhost:8080/", "height": 112} id="YYD6QXgb_UR7" outputId="36363d0a-da3f-48c5-b3d9-81896617bc23"
data = [{'a': 1, 'b': 2, 'c':3},
        {'a':10, 'b': 20, 'c': 30}]
 

df = pd.DataFrame(data)
 

df

# + [markdown] id="MmahmmW2AGL6"
# **Method 6: From list of tuples**

# + colab={"base_uri": "https://localhost:8080/", "height": 175} id="Wm-5oDTIAJjo" outputId="0406c6c4-e6d7-4525-a5a7-22b6efc2e9a8"
# List1
Name = ['tom', 'krish', 'nick', 'juli']
   
# List2
Age = [25, 30, 26, 22]

#List 3

Rank=[1,2,3,4]

# merge list with zip() and then cast to list.
list_of_tuples = list(zip(Name, Age,Rank))

# Converting lists of tuples into pandas Dataframe.
df = pd.DataFrame(list_of_tuples,
                  columns = ['Name', 'Age','Rank'])
    

df

# + [markdown] id="xhQ3houCAvuY"
# **Method 7: From Dicts of pandas series**

# + id="C3jndbfeF-1V" outputId="e91841f7-a1ed-4db3-b1cb-3485bf5a87e8" colab={"base_uri": "https://localhost:8080/", "height": 175}
#List
author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']
article = [210, 211, 114, 178]

#Create pandas series from list  
auth_series = pd.Series(author)
article_series = pd.Series(article)

#Create dict from pandas series  
frame = { 'Author': auth_series, 'Article': article_series }
  
df = pd.DataFrame(frame)

 
df


#How to add series externally in dataframe

age = [21, 21, 24, 23]
  
df['Age'] = pd.Series(age)


# Print data. 
df

# + [markdown] id="Jk42mSYAGb-V"
# **Method 8 : From Blank dataframe**

# + id="-XI4lID9Ghvk" outputId="120dc0e5-c1c5-4621-93af-2777ef3a6232" colab={"base_uri": "https://localhost:8080/", "height": 112}
# Initialize a blank dataframe 
df = pd.DataFrame(columns = ['year','make','model'])
# Add records to dataframe using the .loc function
df.loc[0] = [2014,"toyota","corolla"] 
df.loc[1] = [2018,"honda","civic"] 
df


# + [markdown] id="jvs7dv1mGuQj"
# **Method 9 : using read_csv method**

# + colab={"base_uri": "https://localhost:8080/", "height": 143} id="366EAn1Pao3D" outputId="0de3d6f7-2c4f-407a-a2bf-34c900f9526e"
#Using file path or URL

df=pd.read_csv('https://raw.githubusercontent.com/programres1/DataFrame/main/001/test.csv')
df

#df=pd.read_csv('https://raw.githubusercontent.com/programres1/DataFrame/main/001/titanic.csv')
#print(df)
# Using a csv like string
#from io import StringIO
#f = StringIO('year,make,model\n2014,toyota,corolla\n2018,honda,civic\n2020,hyndai,accent\n2017,nissan,sentra')
#df = pd.read_csv(f)
#df


# + [markdown] id="fohNXM9QbnE5"
# **Method 10 : using read_json method**

# + colab={"base_uri": "https://localhost:8080/", "height": 175} id="ENqnScBsbEtC" outputId="c9ac4b4b-0100-4ed4-ea99-13a5fb422387"
#Using file path or URL

df = pd.read_json('https://raw.githubusercontent.com/programres1/DataFrame/main/001/test.json',lines=True)
df

df = pd.read_json('https://jsonplaceholder.typicode.com/photos')
df


# Using a json like string
from io import StringIO
f = StringIO('{"year": "2014", "make": "toyota", "model": "corolla"}\n{"year": "2018", "make": "honda", "model": "civic"}\n{"year": "2020", "make": "hyndai", "model": "accent"}\n{"year": "2017", "make": "nissan", "model": "sentra"}')
df = pd.read_json(f,lines=True)
df


StarcoderdataJupyterScriptsDedupFiltered