[Python data analysis] Pandas common operations (1)

Hits: 0

[]Pandas is built on Numpy and was originally used as a financial data analysis tool, so pandas has good support for time series analysis [.]
Two [data structures] of pandas : Series and DataFrame


import pandas as pd
from pandas import Series
obj=Series([4,7,-5,3])
print(obj)

0 4
1 7
2 -5
3 3
dtype: int64

#index
obj.index

RangeIndex(start=0, stop=4, step=1)

#values
obj.values

RangeIndex(start=0, stop=4, step=1)

obj2=Series([4,7,-5,3],index=['3/1','3/2','3/3','3/4'])
print(obj2)

3/1 4
3/2 7
3/3 -5
3/4 3
dtype: int64

obj2.index

Index([‘3/1’, ‘3/2’, ‘3/3’, ‘3/4’], dtype=‘object’)

obj2.values

array([4, 7, -5, 3], dtype=int64)

obj2[obj2>0]

3/1 4
3/2 7
3/4 3
dtype: int64

#in
print('3/3'in obj2)

print('3/6' in obj2)

True
False

# Create a Series from a dictionary 
dict1={ '3/1' :4, '3/2' :7, '3/3' :-5, '3/4' :3}
 print (dict1)

{‘3/1’: 4, ‘3/2’: 7, ‘3/3’: -5, ‘3/4’: 3}

Two, [DataFrame]

# Import DateFrame 
from pandas import DataFrame

#Define 2 lists 
position=[ 'Product Manager' , 'Data Analyst' , 'Product Manager' , 'Development' , 'UI' ]
company=[ 'Baidu' , '360' , 'Ali' , 'Tencent' , '58' ]

DataFrame([position,company])

#Transpose
jobInfo=DataFrame([position,company]).T
jobInfo

# Specify the column 
jobInfo.columns=[ 'job name' , 'company name' ]
jobInfo

#index
jobInfo.index

RangeIndex(start=0, stop=5, step=1)

jobInfo.index=['a','b','c','d','e']
jobInfo

#reset_index
jobInfo.reset_index()

#reset_index   
jobInfo.reset_index( drop = True ) #Remove index

#head shows the first few lines of
 jobInfo .head (3)

#tail shows the last few lines of
 jobInfo .tail ( 2)

#Get the value of one of the columns 
#Method 1: 
jobInfo [ "Job Name" ]

a Product manager
b Data analyst
c Product manager
d Developer
e UI
Name: job title, dtype: object

#Method 2: 
jobInfo .job name

a Product manager
b Data analyst
c Product manager
d Developer
e UI
Name: job title, dtype: object

#Get the value of a row 
#Method 1: loc 
jobInfo .loc[ "c" ]

Job Title Product Manager
Company Name Ali
Name: c, dtype: object

#Method 2:
 jobInfo .iloc [2]

Job Title Product Manager
Company Name Ali
Name: c, dtype: object

You may also like...

Leave a Reply

Your email address will not be published.