python - Read in data and set it to the index of a DataFrame with Pandas -


i want iterate through rows of dataframe , assign values new dataframe. i've accomplished task indirectly this:

#first read data df1 , assign df2 if happens counter = 0                         #line1 index,row in df1.iterrows():    #line2     value = row['df1_col']          #line3     value2 = row['df1_col2']          #line4     #try unzipping file (pseudo code)                           df2.loc[counter,'df2_col'] = value  #line5         counter += 1                        #line6     #except         print("error, not unzip {}")  #line7  #then set desired index df2 df2 = df2.set_index(['df2_col'])  #line7 

is there way assign values index of df2 directly in line5? sorry original question unclear. i'm creating index based on happening.

there bunch of ways this. according code, you've done created empty df2 dataframe index of values df1.df1_col. directly this:

df2 = pd.dataframe([], df1.df1_col) #                   ^     ^ #                   |     | # specifies no data, yet  | #                        defines index 

if concerned having filter df1 can do:

# cond boolean mask representing condition filter on. # i'll make 1 you. cond = df1.df1_col > 10 df2 = pd.dataframe([], df1.loc[cond, 'df1_col']) 

Comments