python - 合并这些数据框时的 Nan 值

标签 python pandas

我想合并 pandas 中的两个数据框,但我得到的是 Nan 值。

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

为什么我在合并后的数据框中得到 NaN 值??

我需要这样的数据框,我该怎么做??

  sex  length   diameter  height
    2   0.455    0.365     0.095
    2   0.350    0.265     0.090

最佳答案

您得到 NaN 值,因为在左侧 df 和右侧 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

“M”没有与对应的 int 值 2 匹配。 目前还不清楚您在这里要做什么,您将性别特征值转换为相应的 int 值,然后尝试将其合并回来,为什么不直接在 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

关于python - 合并这些数据框时的 Nan 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28274024/

相关文章:

python - 测试设置的继承

javascript - 是否可以用 JavaScript 解析 .apk 文件?

python - python pandas 从现有 csv 文件创建多个 csv 文件

pandas - 如何将数字转换为新数据帧的值?

python - 15 分钟内从 pandas Dataframe 到 dataframe 时间序列 Bins by sum rows

python - gevent 有基本的 http 处理程序吗?

python - 为什么 BernoulliNBC 在 iris 数据集上的表现比 GaussianNBC 或 MultinomialNBC 差?

python - 当文件夹名称中有空格时使用 `os.path.exists` ?

python - Pandas 和 Plotly : how to access data columns in the hover text that are not used to plot the point?

python - 从数据框中选择随机值,以便生成的数据框在 python-pandas 的两列中是唯一的