如何使用数据列表来匹配数据帧中的数据



我得到了一个坐标列表,我需要匹配数据帧中的坐标,该数据帧包含每个坐标的唯一id和索引。我想匹配坐标,并打印列表中每个坐标的id和索引。

例如

List_coords = [[1,2],[3,4],[5,6]]
df = 
Index  ID  Coords
1      23  [1,2] 
2      34  [3,4]
3      45  [4,5]
4      56  [5,6] 

我希望得到1-23、2-34、4-56这样的东西,并将它们保存到另一个列表中。我该怎么做?

这就是你要找的吗?

match = df['Coords'].isin(List_coords)
(df.loc[match, 'Index'].astype(str) + '-' + df.loc[match, 'ID'].astype(str)).tolist()

输出为

['1-23', '2-34', '4-56']

IIUC您想通过将列与"-"连接来从Index、ID列中获取列表,但只针对那些"Coords"在list_Coords中的行?

然后:

m = df['Coords'].isin(List_coords)
out = df.Index.astype(str).add('-').add(df.ID.astype(str))
out = out[m].tolist()

打印(输出(:

['1-23', '2-34', '4-56']

我想你需要

List_coords = [[1,2],[3,4],[5,6]]
df_matched = df[df['Coords'].isin(List_coords)]
output = df_matched[["Index", "ID"]].astype(str).apply(lambda row: row.str.cat(sep="-"), axis=1).values.tolist()
print(output)
>> ['1-23', '2-34', '4-56']

您可以使用Pandas"merge"。该解决方案将两个DataFrames合并在一起:一个具有ids+坐标,另一个是由正在查找的坐标列表组成的。


import pandas as pd
# Create the parent DF 
parent_df = pd.DataFrame([
[23, [1,2]], 
[45, [4,5]], 
[56, [5,6]], 
[34, [3,4]]
], columns=['id', 'coordinates']) 
# Set as string to perform merge
parent_df['coordinates'] = parent_df['coordinates'].astype(str)
# Take a list of input coords, set as a DF
input_coords = [[1,2],[3,4],[5,6],[99,99]]
list_of_list_of_input_coords = [[coord] for coord in input_coords]
input_coords_df = pd.DataFrame(list_of_list_of_input_coords, columns=['coordinates'])
input_coords_df['coordinates'] = input_coords_df['coordinates'].astype(str)
# Merge the DFs together
merged_df = input_coords_df.merge(parent_df, how='left', on=['coordinates'])
final_list = []
# Createa final list of the ID and coordinates
for index, row in merged_df.iterrows():
final_list.append([row['id'], row['coordinates']])

这将是列表中的五个最终结果:

[[23.0, '[1, 2]'], [34.0, '[3, 4]'], [56.0, '[5, 6]'], [nan, '[99, 99]']]

最新更新