python - 如何将系列与数据框合并并保留双方数据

标签 python pandas numpy

Python。如何将系列与数据框合并并保留双方数据

使用 concat,它为我提供了“g_spend”中的所有值,但不是“grouped_cw”中的所有值,leads= NaN

t = pd.concat([pd.DataFrame(grouped_cw), g_spend], ignore_index=False)

t.head()

output:

 id Campaign_ID_name  Month  Account  campaignid  campaign_name cost  leads
0  35119190 brand    2019|08  SU    35119190  Brand     $59 NaN


使用 join,它给我所有来自“grouped_cw”的值,但不是来自“g_spend”的值,leads= NaN 相反...

t = pd.concat([pd.DataFrame(grouped_cw), g_spend], ignore_index=False)

t.head()

output:

    Account Campaign_ID_nameMonthcampaign_namecampaignidcostid  leads
1076533154  NaN NaN NaN NaN NaN NaN NaN 40.0
143679198   NaN NaN NaN NaN NaN NaN NaN 58.0
169278078   NaN NaN NaN NaN NaN NaN NaN 13.0
1729099155  NaN NaN NaN NaN NaN NaN NaN 8.0
2016404066  NaN NaN NaN NaN NaN NaN NaN 6.0

期望的输出:

可以创建一个 for 循环来计算“lead”并放入 g_spend 数据帧中的新列中,不带(join、merge、concat 等)

无论什么有效! :)

   Campaign_ID_name  Month  Account  campaignid  campaign_name  costh     leads
0    35119190   35119190 brand    2019|08  SU   35119190  Brand     $59    391


这是数据,目标是加入然后通过campaignid

g_spend.to_dict()

{'id': {0: 35119190,
  1: 64002140,
  2: 272351300,
  3: 4899110,},
 'Campaign_ID_name': {0: 'brand',
  1: '-',
  2: '-',
  3: 'science',
,
 'Month': {0: '2019|08',
  1: '2019|08',
  2: '2019|08',
  3: '2019|08',
},
 'Account': {0: 'a',
  1: 'a',
  2: 'b',
  3: 'c',
},
 'campaignid': {0: 35119190,
  1: 64002140,
  2: 272351300,
  3: 4899110,
 },
 'campaign_name': {0: 'All_Brand',
  1: 'All',
  2: 'All_GBHS',
  3: 'All_Science',
},
 'cost': {0: '$59,399.37 ',
  1: '$12,660.37 ',
  2: '$5,631.96 ',
}}

grouped_cw.to_dict()

1076533154 引用campaignid 40.0 是潜在客户数量

{'leads': {'1076533154': 40.0,
  '143679198': 58.0,
  '169278078': 13.0,
  '1729099155': 8.0,
}}

最佳答案

to_dict()命令中可以看出,问题在于g_spend.campaignid是数字,而grouped_cw.index是字符串。例如,您可以将 g_spend.campaignid 转换为字符串并合并:

g_spend.campaignid = g_spend.campaignid.astype(str)

g_spend.merge(grouped_cw, left_on='campaignid', right_index=True)

关于python - 如何将系列与数据框合并并保留双方数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139186/

相关文章:

python - 如何在python和go语言之间共享变量?

python - Pandas 数据框和附加对象转换为 JSON

python - 使用 Scipy 拟合 Weibull 分布

python-2.7 - 两个矩阵之间的最短路径

Python。检查索引是否存在于可能的字典列表中

python - 使用 Python 分割 MP3 音频文件

python - PyQt5 : get index of cell widgets and their chosen values

pandas - Pandas 交叉表与 Pandas 数据透视表有何不同?

python - 用列的顺序替换 Pandas 数据框中的值

python - 计算图像python中的角度