gpt4 book ai didi

python - 合并两个数据框,但仅显示一条记录上的合并数据

转载 作者:行者123 更新时间:2023-11-30 21:57:48 24 4
gpt4 key购买 nike

我正在合并两个数据帧,这是我可以做到的。我遇到的问题是仅显示特定记录上的合并数据。两个数据框都有 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)
<小时/>

然后我们使用duplicatedmask

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'])

关于python - 合并两个数据框,但仅显示一条记录上的合并数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55132669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com