Showing posts with label Numpy. Show all posts
Showing posts with label Numpy. Show all posts

Aug 15, 2021

[Python] sort data frame and reset index

import pandas as pd
import numpy as np


n = ["Jake", "Annie", "Charles", "Sam", "David"]
g = [80, 90, 75, 64, 78]

# create a data frame 
df = pd.DataFrame()
df["name"], df["grade"] = n, g 
print(df, "\n")

# sort by name
df.sort_values(by=["name"], ascending=[True], inplace=True)  
print(df, "\n")

# reset index
df.reset_index(inplace=True, drop=True)
print(df, "\n")

[Python] create a new Pandas DataFrame, and add a new column to the data frame

import pandas as pd
import numpy as np


n = ["Annie", "Charles", "David", "Sam"]
g = [80, 90, 75, 78]

# create a data frame using one of lists
df = pd.DataFrame(n, columns=["name"])
print(df, "\n")

# add another list to the data frame
df.insert(len(df.columns), "grade", g)
print(df, "\n")

# dertermine whether pass or not and create a new column for it
df["pass"] = np.where(df["grade"] >=80, "yes", "no")
print(df, "\n")




Aug 9, 2021

[Python] to reset index for a sorted list

import pandas as pd
import numpy as np


data1 = [1, 3, 2, 4]
data2 = [1015, 1014, 1014, 1019]
data3 = [33, 39, 91, 14]

data = [data1, data2, data3]
print('data: ', data, "\n")

data_transposed = np.transpose(data)
print('transposed data: \n', data_transposed, "\n")

df = pd.DataFrame(data_transposed, columns=['quantity', 'date', 'price'])
print('DataFrame: \n', df, "\n")

size = len(df['date'])
evaluation = [df['quantity']*df['price']] 
temp = np.array(evaluation).reshape(size,1) 
df = np.hstack([df, temp]) 
df = pd.DataFrame(df, columns=['quantity', 'date', 'price', 'evaluation'])
print("DataFrame with added column: \n", df, "\n")

df = df.sort_values(['date', 'evaluation'], ascending=[True, True])
df = df[["date", "evaluation", "price", "quantity"]]
print('sorted DataFrame: \n', df, "\n")

df = df.reset_index(drop=True)
print('re-indexed data: \n', df)