Populate column in data frame based on a range found in another dataframe

前端 未结 3 1531
生来不讨喜
生来不讨喜 2021-01-25 18:07

I\'m attempting to populate a column in a data frame based on whether the index value of that record falls within a range defined by two columns in another data frame.

d

3条回答
  •  半阙折子戏
    2021-01-25 18:19

    import pandas as pd
    import numpy as np
    
    # Here is your existing dataframe
    df_existing = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    
    # Create a new empty dataframe with specific column names and data types
    df_new = pd.DataFrame(index=None)
    columns = ['field01','field02','field03','field04']
    dtypes = [str,int,int,int]
    for c,d in zip(columns, dtypes):
        df_new[c] = pd.Series(dtype=d)
    
    # Set the index on the new dataframe to same as existing 
    df_new['new_index'] = df_existing.index
    df_new.set_index('new_index', inplace=True)
    
    # Fill the new dataframe with specific fields from the existing dataframe
    df_new[['field02','field03']] = df_existing[['B','C']]
    print df_new
    

提交回复
热议问题