Home > Net >  How To Create a new DF Column By checking a lookup table and inserting the appropriate value
How To Create a new DF Column By checking a lookup table and inserting the appropriate value

Time:07-24

I have 2 dataframes, the first is a cartesian joined table which has the below structure:

track_x Energy_x Camelot_x BPM_x join track_y Energy_y Camelot_y BPM_y Energy_Distance BPM Distance
Buju Banton - Blessed 5 10A 75 1 Gyptian - Hold You - Hold Yuh 6 4B 67 1 8

where it has around 10k rows with every track referencing every other track.

I then have a second table which i am using to store the distances between camelot_x & camelot_y which has the columns and indexes as the 10A, 4B value for example and then the value as an integer.

1A 1B 2A
1A 0 1 1
1B 1 0 1
2A 1 1 0

I am struggling however to retrieve this corresponding value.

I have used code:

def harmonic_distance_lookup(x, y):
    value = distance_df.lookup(x, y)
    return value


ct_df["Harmonic Distance"] = ct_df.apply(harmonic_distance_lookup(ct_df["Camelot_x"], ct_df["Camelot_y"]), axis=1)

However this just spins forever and doesn't seem to be doing anything.

Is there a better method of doing this? I want to check the distance between camelot_x & camelot_y for every row and append it to a new column

Expected output: |track_x|Energy_x|Camelot_x|BPM_x|join|track_y|Energy_y|Camelot_y|BPM_y|Energy_Distance|BPM Distance| Harmonic Distance| |-|-|-|-|-|-|-|-|-|-|-|-| |Buju Banton - Blessed|5|10A|75|1|Gyptian - Hold You - Hold Yuh|6|4B|67|1|8|6|

Working Answer:

def harmonic_distance_lookup(x, y):
    value = distance_df.at[x, y]
    return value


ct_df["Harmonic Distance"] = ct_df.apply(lambda x: harmonic_distance_lookup(x["Camelot_x"], x["Camelot_y"]), axis=1)
ct_df

CodePudding user response:

Try this:

ct_df.apply(lambda x: harmonic_distance_lookup(x["Camelot_x"], x["Camelot_y"]), axis=1)

Also df.lookup is deprecated in 1.2.0. You might want to look at df.at.

  • Related