Home > database >  in python/pandas, how to add lead vaue and filter the dataframe
in python/pandas, how to add lead vaue and filter the dataframe

Time:08-08

In python/pandas, 1) How to add new variable (the lead_value as image) ? 2) How to filter the dataframe which type include ":" ?

import pandas as pd
ori_df=pd.DataFrame()
ori_df=pd.DataFrame([['a','1'],['w:','z'],['t','6'],['f:','z'],['a','2']],
                    columns=['type','value']
                    )

enter image description here

CodePudding user response:

import pandas as pd

ori_df = pd.DataFrame(
    [['a','1'],['w:','z'],['t','6'],['f:','z'],['a','2']],
    columns=['type','value']
)

ori_df['lead_value'] = ori_df['value'].shift(-1).fillna(0)

ori_df_filtered = ori_df[ori_df['type'].apply(lambda t: ':' in t)]
print(ori_df_filtered)

prints

index type value lead_value
1 w: z 6
3 f: z 2
  • Related