You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Make a new standalone DF
newDf = df_first.copy(deep=True)
# Matching specific value
newDf = df.loc[df["Year"] == 2024]
# Transpose a Row to a list
stocks = ['sp500','nasdaq']
row = df.iloc[0]
df_temp = row[stocks].transpose().to_frame(name="value").sort_values(by=["value"], ascending=False)
# If the names are in the index. Take the 10 first stocks and convert it to a list
stocklist = df.head(10).index.to_list()
# Make a new DF where a row with the stockname in the col stocknames match a list of stocks (stocklist)
df_selected = df_stocks[df_stocks['stocknames'].isin(stocklist)]
# Pandas series, to a list
s = pd.Series([1, 2, 3])
list = s.to_list()
# OR
idx = pd.Index([1, 2, 3])
list = idx.to_list()
# Insert last (append)df.loc[len(df)] = [name, address, variable2]
# Inser a new columndf["myCol"] =df_1["cars"]+df_1["bikes"]
Insert to a list
Take a DF with one column and choose rows by index and insert into a list
myList.append(df.iloc[last:last+nr+add])
# Append a list as a row in a list (as Pandas series, per list row)myList.append(pd.Series(anotherList))
Delete
Delete a row
# Remove the first rowdf.drop(index=df.index[0], axis=0, inplace=True)
# Remove the last rowdf.drop(df.tail(1).index, inplace=True)
# Delete rows from the beginning to first non-NAN valueidx=df.first_valid_index()
df=df.iloc[idx-1:]
# Delete NA valuesdf=df.dropna()
# All rows where age is 21rows=df[df["Age"] ==21].indexdf.drop(rows, inplace=True)
# All rows where age is 20-22rows=df[(df["Age"] >=20) & (df["Age"] <=22)].indexdf.drop(rows, inplace=True)
# All rows where Department = HRrows=df[df["Department"] =="HR"].indexdf.drop(rows, inplace=True)
# All rows where column matches something in a listrows=df[df["Department"].isin(["HR", "Finance"])].indexdf.drop(rows, inplace=True)
# All rows where Department is not ITrows=df[df["Department"] !="IT"].indexdf.drop(rows, inplace=True)
# Remove rows where column values are not the same, but keep if a column value is empty (col called V2 and V3)# It take the value of V2 if V3 is empty and then compare, but in the end takes the original valuesnewDf=df[df.V3.fillna(df.V2).eq(df.V2)]
Delete a column
# 3 Different alternativesdelmyDF['columnName']
myDF.pop('columnName')
myDF=myDF.drop(['columnName'], axis=1)
# Multi deletemyDF=myDF.drop(['columnName', 'anotherName'], axis=1)
# By indexdf.drop(df.columns[0], axis=1, inplace=True)
# Delete na valuesdf=df.dropna()
Recalculate
# Recalculate the indexdf=df.reset_index(drop=True)