【问题标题】:Pandas: merging two dataframesPandas:合并两个数据框
【发布时间】:2014-07-28 18:22:18
【问题描述】:

对两个 pandas 数据帧的 MERGE 操作的输出没有产生预期的结果:

**dfmatrix**:
    …   young   label   filename
0   …   1       neg     cv005_29357
1   …   0       neg     cv006_17022
2   …   0       neg     cv007_4992
3   …   1       neg     cv008_29326
4   …   1       neg     cv009_29417

**dfscores**:
   filename  score
0  cv005_29357   -10
1  cv006_17022   5

dfnew = pandas.merge(dfmatrix, dfscores, on='filename', how='outer', left_index=False, right_index=False)

**dfnew**:
   …    young   label   filename    score_y
0  …    0       neg     cv005_29357 NaN
1  …    1       neg     cv006_17022 NaN
2  …    0       neg     cv007_4992  NaN
3  …    0       neg     cv008_29326 NaN
4  …    1       neg     cv009_29417 NaN

Excpected Output:

**dfnew**:
   …    young   label   filename    score_y
0  …    0       neg     cv005_29357 -10
1  …    1       neg     cv006_17022 5
2  …    0       neg     cv007_4992  NaN
3  …    0       neg     cv008_29326 NaN
4  …    1       neg     cv009_29417 NaN

我做错了什么?

更新:this post 建议使用 MERGE 来连接两个数据框

【问题讨论】:

  • 将这些显示为已在帧中读取;指标非常重要。
  • 在 pandas 中工作 0.14.1 你在运行什么版本?
  • @Jeff,我现在已经添加了索引
  • @EdChum, pip show pandas: 0.14.1
  • 您的输出与您的代码不匹配,如果没有冲突,您如何获得score_y 的列?您在 dfscores 中只有 score 列,而在其他 df 中没有。

标签: python pandas


【解决方案1】:

问题出在文件级别:正在读取的dfscores 文件的filename 列中的条目有一个trailing whitespace,这导致JOIN 失败。承认,这对我来说不是一个光荣的时刻,但尽管如此,这些事情还是发生了,我认为值得发布答案,因为它可能会发生在其他经验不足的编码人员身上。

自动化流程:

dfscores['filename'] = dfscores['filename'].map(lambda x: x.strip())

来源:Pandas DataFrame: remove unwanted parts from strings in a column

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 2018-03-14
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2020-02-19
    • 2023-03-09
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多