Chrome Extension

Create pandas DataFrame and add columns and rows to it

There are several ways to create DataFrame in pandas and add data to it as columns and rows.
import pandas as pd
  
#first method - create empty dataframe
df = pd.DataFrame()

# append columns and rows to this dataframe
df['username'] = ['john', 'neil', 'curtis']
df['status'] = ['active', 'disabled', 'active']
print(df)

#----------------------------------------------------------------------------------#

#second method - create dataframe with columns
df = pd.DataFrame(columns = ['username', 'status'])

# append rows to the abo
df = df.append({'username' : 'john', 'status' : 'active'}, ignore_index = True)
df = df.append({'username' : 'neil', 'status' : 'disabled'}, ignore_index = True)
df = df.append({'username' : 'curtis', 'status' : 'active'}, ignore_index = True)
print(df)

#----------------------------------------------------------------------------------#

#make data frame with rows having - NaN values at index - a, b and c
df = pd.DataFrame(columns = ['username', 'status'], index = ['a', 'b', 'c'])
print(df)
#  +---+----------+--------+
#  |   | username | status |
#  +---+----------+--------+
#  | a |      NaN |    NaN |
#  | b |      NaN |    NaN |
#  | c |      NaN |    NaN |
#  +---+----------+--------+

# add rows at already created indexes
df.loc['a'] = ['john', 'active']
df.loc['b'] = ['neil', 'disabled']
df.loc['c'] = ['curtis', 'active']
print(df)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Was this helpful?
0 Comments