I have a dataframe that looks like below, what I would like to do is create a single column for when the value in 'Name' matches the column header. I have tried df.lookup, lists, etc. but keep getting errors.
Existing Dataframe
Name | Proj | Ceil | Floor | sim_id | lj | nc | bn | jl | |
---|---|---|---|---|---|---|---|---|---|
0 | lj | 22.72 | 37 | 9.8 | 0 | 50 | 55 | 25 | 20 |
1 | lj | 22.72 | 37 | 9.8 | 1 | 49 | 54 | 24 | 19 |
2 | lj | 22.72 | 37 | 9.8 | 2 | 33 | 2 | 27 | 18 |
3 | lj | 22.72 | 37 | 9.8 | 3 | 14 | 60 | 17 | 35 |
4 | lj | 22.72 | 37 | 9.8 | 4 | 45 | 40 | 48 | 10 |
5 | lj | 22.72 | 37 | 9.8 | 5 | 10 | 15 | 35 | 30 |
6 | lj | 22.72 | 37 | 9.8 | 6 | 57 | 75 | 27 | 27 |
7 | lj | 22.72 | 37 | 9.8 | 7 | 22 | 17 | 18 | 11 |
8 | lj | 22.72 | 37 | 9.8 | 8 | 3 | 6 | 26 | 36 |
9 | lj | 22.72 | 37 | 9.8 | 9 | 12 | 32 | 5 | 3 |
10 | nc | 13.24 | 30.9 | 4.4 | 0 | 50 | 55 | 25 | 20 |
11 | nc | 13.24 | 30.9 | 4.4 | 1 | 49 | 54 | 24 | 19 |
12 | nc | 13.24 | 30.9 | 4.4 | 2 | 33 | 2 | 27 | 18 |
Desired Output
Name | Proj | Ceil | Floor | sim_id | lj | nc | bn | jl | new_val | |
---|---|---|---|---|---|---|---|---|---|---|
0 | lj | 22.72 | 37 | 9.8 | 0 | 50 | 55 | 25 | 20 | 50 |
1 | lj | 22.72 | 37 | 9.8 | 1 | 49 | 54 | 24 | 19 | 49 |
2 | lj | 22.72 | 37 | 9.8 | 2 | 33 | 2 | 27 | 18 | 33 |
3 | lj | 22.72 | 37 | 9.8 | 3 | 14 | 60 | 17 | 35 | 14 |
4 | lj | 22.72 | 37 | 9.8 | 4 | 45 | 40 | 48 | 10 | 45 |
5 | lj | 22.72 | 37 | 9.8 | 5 | 10 | 15 | 35 | 30 | 10 |
6 | lj | 22.72 | 37 | 9.8 | 6 | 57 | 75 | 27 | 27 | 57 |
7 | lj | 22.72 | 37 | 9.8 | 7 | 22 | 17 | 18 | 11 | 22 |
8 | lj | 22.72 | 37 | 9.8 | 8 | 3 | 6 | 26 | 36 | 3 |
9 | lj | 22.72 | 37 | 9.8 | 9 | 12 | 32 | 5 | 3 | 12 |
10 | nc | 13.24 | 30.9 | 4.4 | 0 | 50 | 55 | 25 | 20 | 55 |
11 | nc | 13.24 | 30.9 | 4.4 | 1 | 49 | 54 | 24 | 19 | 54 |
12 | nc | 13.24 | 30.9 | 4.4 | 2 | 33 | 2 | 27 | 18 | 2 |
import pandas as pd
data1 = [['lj', 22.72, 37, 9.8], ['nc', 13.24, 30.9, 4.4], ['bm', 13.77, 26.3, 9.3], ['jl', 12, 25.9, 7.2]]
df = pd.DataFrame(data1, columns=['Name', 'Proj', 'Ceil', 'Floor'])
data2 = [['0', 50, 55, 25, 20], ['1', 49, 54, 24, 19], ['2', 33, 2, 27, 18], ['3', 14, 60, 17, 35],
['4', 45, 40, 48, 10],
['5', 10, 15, 35, 30], ['6', 57, 75, 27, 27], ['7', 22, 17, 18, 11], ['8', 3, 6, 26, 36], ['9', 12, 32, 5, 3]]
df2 = pd.DataFrame(data2, columns=['sim_id', 'lj', 'nc', 'bn', 'jl'])
df3 = df.assign(temp=1).merge(df2.assign(temp=1), on='temp').drop('temp', 1)
df = df3
df['new_val'] = df.lookup(df.index,df.Name)
df['new_val'] = df.lookup(df.index,df.Name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.