简体   繁体   English

Python 合并数据帧

[英]Python Merging data frames

In python, I have a df that looks like this在 python 中,我有一个看起来像这样的 df

Name    ID
Anna    1
Polly   1
Sarah   2
Max     3
Kate    3
Ally    3
Steve   3

And a df that looks like this还有一个看起来像这样的df

Name    ID
Dan     1
Hallie  2
Cam     2
Lacy    2
Ryan    3
Colt    4
Tia     4

How can I merge the df's so that the ID column looks like this如何合并 df 以使 ID 列看起来像这样

Name    ID
Anna    1
Polly   1
Sarah   2
Max     3
Kate    3
Ally    3
Steve   3
Dan     4
Hallie  5
Cam     5
Lacy    5
Ryan    6
Colt    7
Tia     7

This is just a minimal reproducible example.这只是一个最小的可重现示例。 My actual data set has 1000's of values.我的实际数据集有 1000 个值。 I'm basically merging data frames and want the ID's in numerical order (continuation of previous data frame) instead of repeating from one each time.我基本上是在合并数据帧,并希望 ID 以数字顺序(前一个数据帧的延续)而不是每次从一个重复。 I know that I can reset the index if ID is a unique identifier.我知道如果 ID 是唯一标识符,我可以重置索引。 But in this case, more than one person can have the same ID.但在这种情况下,可以有多个人拥有相同的 ID。 So how can I account for that?那么我该如何解释呢?

From the example that you have provided above, you can observe that we can obtain the final dataframe by: adding the maximum value of ID in first df to the second and then concatenating them, to explain this better:从您上面提供的示例中,您可以观察到我们可以通过以下方式获得最终的 dataframe:将第一个 df 中 ID 的最大值添加到第二个,然后将它们连接起来,更好地解释这一点:

Name  df2   final_df
Dan   1     4

This value in final_df is obtained by doing a 1+(max value of ID from df1 ie 3) and this trend is followed for all entries for the dataframe. final_df 中的该值是通过执行 1+(来自 df1 的 ID 的最大值,即 3)获得的,并且对于 dataframe 的所有条目都遵循此趋势。

Code:代码:

import pandas as pd

df = pd.DataFrame({'Name':['Anna','Polly','Sarah','Max','Kate','Ally','Steve'],'ID':[1,1,2,3,3,3,3]})
df1 = pd.DataFrame({'Name':['Dan','Hallie','Cam','Lacy','Ryan','Colt','Tia'],'ID':[1,2,2,2,3,4,4]})

max_df = df['ID'].max()
df1['ID'] = df1['ID'].apply(lambda x: x+max_df)
final_df = pd.concat([df,df1])
print(final_df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM