Python Tips DataFrame & Dictionary
Pandas Dataframe Quick References
Given:
· Import pandas as pd
· Name=[‘Rob’, ‘John’, ‘Janice’]
· Age=[25,35,45]
Pointers:
1. How to define a dataframe from two equal size lists?
· df=pd.DataFrame({‘Name’: Name, ‘Age’:Age})
2. How to add another list to the dataframe df
· Label=[‘a’, ‘b’, ‘c’]
· df[‘label’]=label
3. How to get the shape of a Pandas dataframe?
· r, c = df.shape
4. How to add lists to a dataframe?
· Label=[‘a’, ‘b’, ‘c’]
· df[‘label’]=label
5. How to get value of a particular cell k?
· df[‘label’].values[k]
6. How to get a subset of a dataframe?
· Result_df = df[[‘label’, ‘size’]]
7. How to write a dataframe into a csv file?
· df.to_csv(file_path,header=None,Index=False)
8. How to find out values of a corresponding column based on a key column value?
a. Ex: find out age of Rob?
b. age_val= df[df[‘name’]== ‘Rob’].[‘age’].value[0]
Dictionary Tips:
9. How to build a disctionary from two lists
· Name=[‘Rob’, ‘John’, ‘Janice’]
· Age=[25,35,45]
Res=dict(zip(Name,Age))
10. Find what is the minimum age from a dictionary?
· Min(res.values())
11. Find what is the person’s name with minimum age?
· Min(res,key=res.get)