python - 合并两个数据框,但仅在一条记录上显示合并数据
问题描述
我正在合并两个数据框,我可以这样做。我遇到的麻烦只是在特定记录上显示合并数据。这两个数据框都有 ID 和日期。但是只有一个日期应该有与之相关的回复,但我仍然想显示这两个记录。您能提供的任何帮助将不胜感激。
例如:
ID | Date | Name | Question_1 | Response_1
12 12/4/2018 John question text response text
12 1/1/2019 John question text response text
16 2/23/2019 Carol question text response text
23 3/01/2019 Gary question text response text
这是我需要的:
ID | Date | Name | Question_1 | Response_1
12 12/4/2018 John question text response text
12 1/1/2019 John
16 2/23/2019 Carol question text response text
23 3/01/2019 Gary question text response text
代码:
def data_validate(files, study):
df1 = pd.read_csv(files[0])
df2 = pd.read_csv(files[1])
df_merge = pd.merge(df1, df2, on='ID', how='left')
df_merge.to_csv('results.csv', index=False)
print(df_merge)
解决方案
第一次使用将您的日期转换回日期时间格式to_datetime
df.Date=pd.to_datetime(df.Date)
然后我们duplicated
使用mask
s=df.ID.duplicated()
df[['Question_1','Response_1']]=df[['Question_1','Response_1']].mask(s,'')
df
Out[287]:
ID Date Name Question_1 Response_1
0 12 2018-12-04 John questiontext responsetext
1 12 2019-01-01 John
2 16 2019-02-23 Carol questiontext responsetext
3 23 2019-03-01 Gary questiontext responsetext
在这里,我假设您的数据框已经排序,如果不使用sort_values
喜欢 :
df=df.sort_values(['ID','Date'])
推荐阅读
- linux - wget 无法在终端中使用树莓派项目 pacman
- hibernate - 针对 H2 的 spring data JPA 查询失败,找不到模式
- microsoft-graph-api - Microsoft Graph API 停止在一个驱动器项目中继承权限
- java - .fillOval 坐标在 repaint() 期间未更新
- python - 弹性搜索查询从 regexp 输入参数中查找列表中值的完全匹配
- javascript - 在 vue.js 中显示原始图像内容类型
- ruby-on-rails-5 - ActiveRecord 生成条件 SQL
- java - java gradle 找不到要编译的github仓库
- sqlite - sqlite julianday 添加秒数的结果不正确
- javascript - 如何设置特定滑块的状态?