【问题标题】:Pandas merge with "left" option is losing rows in left data frame熊猫与“左”选项合并正在丢失左侧数据框中的行
【发布时间】:2022-01-23 14:29:17
【问题描述】:

我有 2 个数据框。 第一个(左)数据框有 5,000,000 行,第二个只有 47,000 行。 当我尝试使用“左”选项合并这些数据框时,我只得到 47.000 行。

first = pd.read_csv('first.csv')
second = pd.DataFrame(first['id'])
second.drop_duplicates(inplace=True)
second['mark'] = second['id'].apply(lambda x:get_mark(x))
new=first.merge(second,how='left',on='id')

在这里我得到了 47,000 个原始数据。

重新打开第一个数据框。

first = pd.read_csv('first.csv')
new=first.merge(second,how='left',on='id')

我在这里得到了 5,000,000 个带有标记的原始数据。

如何避免重新加载第一个数据帧或解决此问题?

【问题讨论】:

  • 您能提供数据集的链接吗?如果需要,您可以删除敏感数据。还提供完整代码(读取、索引设置、形状、合并等)
  • 不幸的是,所有数据都是敏感的(客户日志),所以我无法访问数据。我已将所有代码添加到主帖中。

标签: python pandas dataframe merge


【解决方案1】:

我没有发现代码有任何问题,所以您需要查看数据:

import pandas as pd
import numpy as np
import sys


print('python version ', sys.version)
def get_mark(x):
    # just random data
    return np.random.normal(x, 2) 

# Simulate data
first_series = np.random.randint(0, 47000, 5000000)
first = pd.DataFrame(first_series, columns=['id'])

second = pd.DataFrame(first['id'])
second.drop_duplicates(inplace=True)
second['mark'] = second['id'].apply(lambda x:get_mark(x))

print('Shape first', first.shape)
print('Shape second', second.shape)

# merge
new=first.merge(second,how='left',on='id')


print('Shape new',  new.shape)
python version  3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
Shape first (5000000, 1)
Shape second (47000, 2)
Shape new (5000000, 2)

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2017-12-28
    相关资源
    最近更新 更多