在不同列的两个单独的 excel 文件中查找不同的行并将它们组合在一起



我是完全陌生的,所以我没有任何代码要呈现。

我需要python 3.x的帮助,最好是pandas包。

我有两个单独的 excel 文件。在第一个 excel 文件中,我想按行中的值查找行,该值看起来像K232999.它们位于第二列中。

然后我想使用与这些名称关联的时间值,该值位于第一列中,格式为dd/mm/yyyy hh:mm,并使用它来查找第二个 excel 文件中的行并提取它们。第二个文件中的时间值也位于第一列中,并且格式相同。

最重要的是,时间间隔也很重要:

我需要从1.9.2019. 12:55 - 2.9.2019. 10:352.9.2019. 09:46 - 3.9.2019. 02:51的间隔进行K324645,然后在不同的 excel 文件中找到相同的间隔,并将它们组合到单独的 excel 中或内存中的某个地方,以便我可以使用它们,或者最好两者兼而有之。例如:

Excel 1:

1.9.2019. 12:55 K324645
1.9.2019. 17:55 K324645
2.9.2019. 02:51 K324645
2.9.2019. 10:35 K324645
2.9.2019. 12:55 FGJFJKH
2.9.2019. 17:12 SAFFAFA
2.9.2019. 19:15 SGDFGDS
3.9.2019. 11:46 K324645
3.9.2019. 17:55 K324645
3.9.2019. 20:51 K324645
3.9.2019. 05:32 FDSJFJKH
3.9.2019. 10:12 SAFFAFA
3.9.2019. 17:12 SGDFGDS

Excel 2:

1.9.2019. 12:57 345,7
1.9.2019. 17:50 218,3
2.9.2019. 02:53 323,4
2.9.2019. 10:29 125,5
2.9.2019. 13:00 215,8
2.9.2019. 17:09 232,7
3.9.2019. 09:53 188.7
3.9.2019. 10:45 656.5
3.9.2019. 12:26 355,2
3.9.2019. 17:45 656.5
3.9.2019. 20:49 268.4

最终结果:

1.9.2019. 12:55 K324645 345,7
1.9.2019. 17:55 K324645 218,3
2.9.2019. 02:51 K324645 323,4
2.9.2019. 10:35 K324645 125,5 
3.9.2019. 11:46 K324645 355,2
3.9.2019. 17:55 K324645 656,5
3.9.2019. 20:51 K324645 268,4

请注意,表中的日期不同。我必须在第一个的时间范围内从秒中提取值。

你说你是全新的,所以我不确定你在这方面走了多远。 如果已将两个文件导入数据帧,则需要将两个数据帧中的DateTime列重命名为相同的名称。然后使用内部合并。

df3 = pd.merge(df1, df2, on='DateTime', how='inner') # merge the dataframes
df3['DateTime'] = pd.to_datetime(df3['DateTime']) # convert column to date/time format  

此时,我将数据帧一分为二。一个时间在 1/9/2019 12:55 和 2/9/2019 10:35 之间。另一个时间介于 2/9/2019 09:46 和 3/9/2019 02:51 之间。然后将这两者重新合并在一起。

firstset = df3[(df3['DateTime'].astype(str) >= '2019-01-09 12:55:00') & (df3['DateTime'].astype(str) < '2019-02-09 10:35:01')]
secondset = df3[(df3['DateTime'].astype(str) >= '2019-02-09 09:46:00') & (df3['DateTime'].astype(str) < '2019-03-09 02:51:01')]  
final = pd.concat([firstset, secondset]).drop_duplicates()

这应该完成您想要的。不过,这可能不是最快的方法。

第一次使用:

import pandas as pd
df1=pd.read_excel(file1)
df2=pd.read_excel(file2)
pd.to_datetime(df1['Time_Column_name'].str.strip(),format='%H:%M:%S')
pd.to_datetime(df2['Time_Column_name'].str.strip(),format='%H:%M:%S')

然后使用以下方法合并 2 个数据帧:

pd.merge(df1,df2,how=inner)

最新更新