合并 pandas 中的两个数据框 [英] Merge two dataframe in pandas

查看:42
本文介绍了合并 pandas 中的两个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码合并两个 csv(数据框):

I am merging two csv(data frame) using below code:

import pandas as pd
a = pd.read_csv(file1,dtype={'student_id': str})
df = pd.read_csv(file2)
c=pd.merge(a,df,on='test_id',how='left')
c.to_csv('test1.csv', index=False)

我有以下 CSV 文件

I have the following CSV files

文件 1:

test_id, student_id
1, 01990
2, 02300
3, 05555

文件 2:

test_id, result
1, pass
3, fail

合并后

test_id, student_id , result
1, 1990, pass
2, 2300,
3, 5555, fail

如果您注意到 student_id 在开头附加了 0 并且它应该被视为文本,但是在合并和使用 to_csv 函数后,它会将其转换为数字并删除前导 0.

If you notice student_id has 0 appended at the beginning and it's supposed to be considered as text but after merging and using to_csv function it converts it into numeric and removes leading 0.

即使在 to_csv 之后,如何将列保留为文本"?

How can I keep the column as "text" even after to_csv?

我认为它的 to_csv 函数可以再次保存为数字在读取 csv 时添加 dtype={'student_id': str} .. 但在将其保存为 to_csv .. 时再次将其转换为数字

I think its to_csv function which saves back again as numeric Added dtype={'student_id': str} while reading csv.. but while saving it as to_csv .. it again convert it to numeric

推荐答案

a = pd.read_csv(file1, dtype={'test_id': object})
df = pd.read_csv(file2, dtype={'test_id': object})

==============================================================

==============================================================

In[28]: pd.merge(a, b, on='test_id', how='left')
Out[28]: 
  test_id   student_id  result
0      01         1990    pass
1      02         2300     NaN
2     003         5555    fail

这篇关于合并 pandas 中的两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆