I am want to merge two data frames in pandas but I am getting Nan values.
data_orig = url
data_orig.head(3) #data frame 1
sex length diameter height
0 M 0.455 0.365 0.095
1 M 0.350 0.265 0.090
2 F 0.530 0.420 0.135
def parse_label(label):
options = {'I': 0, 'F': 1, 'M': 2}
return options[label]
data = pd.DataFrame()
data['sex'] = data_orig['sex'].map(parse_label)
data.head() #data frame 2
sex
0 2
1 2
2 1
3 2
pd.merge(data, data_orig, on ='sex', how= 'left')
sex length diameter height
2 NaN NaN NaN
2 NaN NaN NaN
Why do I get NaN values in my merged data frame??
I need a data frame like this, how do i do that??
sex length diameter height
2 0.455 0.365 0.095
2 0.350 0.265 0.090
You get NaN
values because there are no matches for your values in the left hand side df with the right hand side df:
In [3]:
data
Out[3]:
sex
0 2
1 2
2 1
In [4]:
df
Out[4]:
sex length diameter height
0 M 0.455 0.365 0.095
1 M 0.350 0.265 0.090
2 F 0.530 0.420 0.135
There are no matches for 'M' with the corresponding int value 2. It's unclear what you are trying to do here, you performed a conversion of your sex character values to their corresponding int value and then you try to merge this back, why not just convert them in the orig df:
In [6]:
df['sex'] = df['sex'].map(parse_label)
df
Out[6]:
sex length diameter height
0 2 0.455 0.365 0.095
1 2 0.350 0.265 0.090
2 1 0.530 0.420 0.135
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.