[Python Cookbook] Pandas: 3 Ways to define a DataFrame

Using Series (Row-Wise)

import pandas as pd
purchase_1 = pd.Series({'Name': 'Chris',
                        'Item Purchased': 'Dog Food',
                        'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Kevyn',
                        'Item Purchased': 'Kitty Litter',
                        'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Vinod',
                        'Item Purchased': 'Bird Seed',
                        'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])
df.head()

 

Using Series (Column-Wise)

s1 =pd.Series([.25,.5,.75,1],index = ['a','b','c','d']
s2 =pd.Series([.5,.75,1,.25],index = ['a','b','c','d']
df = pd.DataFrame({’s1’:s1,’s2’:s2})
print (df)

 

 

Using Dictionary (Columnwise)

data = {'Fruit':['Apple','Pear','Strawberry'],
       'Amount':[3,2,5],
       'Price':[10,9,8]}
df = DataFrame(data)
print(df)

 

 

Using Nested Dictionary

The outer dictionary is columnwise and the inner dictionary is rowwise.

data = {'Amount':{'Apple':3,'Pear':2,'Strawberry':5},
       'Price':{'Apple':10,'Pear':9,'Strawberry':8}}
df = DataFrame(data)
print(df)

 

posted @ 2019-01-30 02:30  Sherrrry  阅读(262)  评论(0编辑  收藏  举报