Python逻辑迭代比较两个文件并建立父子关系

2024-03-28 19:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我解释一下更简单的逻辑吗?我已经挠头两天了。你知道吗

问题:-我有两个CSV文件。尝试建立父/子关系,直到关系耗尽b/w这两个文件。你知道吗

Assume, both the files have 2 columns A, B in 1st csv and C, D in second CSV.

"A" should be matched with "C" and for the matching rows [Inner Join], take the "D" and compare it with "B" [Again an inner join]. Then again, from the result, A should be matched against "C" till the relation or chain stops somewhere.

基本上,在我的问题中,B是D的孩子,B本身可能有另一个孩子。你知道吗

我不确定我说得很清楚

谢谢你主动帮忙。我已经创建了虚拟数据。请看是否有用

在两个csv文件中输入数据,如下所示

A   B            C    D
310 9000        310 8000                                                                         
320 8000        320 2000   
330 2000        330 1000
340 1000        350 2500

在新文件或数据帧:-链停在1000,因为340在第二个csv中没有行。你知道吗

预期产量数据:-你知道吗

    A   B    C   D    E   F
1. 310 8000 320 2000 330 1000

Tags: and文件csvthe数据in关系with
1条回答
网友
1楼 · 发布于 2024-03-28 19:19:30

据我所知,我认为这是你需要的:

df1

    A   B
0   310 9000
1   320 8000
2   330 2000

df2

     C  D
0   310 8000
1   320 2000
2   330 1000

合并dfs:

merged_df = pd.merge(df1, df2, left_on = ['A'], right_on = ['C'])
merged_df
     A   B       C  D
0   310 9000    310 8000
1   320 8000    320 2000
2   330 2000    330 1000

当B>;D时,假设D是B的子级:

result = merged_df.loc[merged_df['B']>merged_df['D'],['C', 'D']].values.ravel()
result
array([ 310, 8000,  320, 2000,  330, 1000], dtype=int64)

将它们转换为系列:

pd.Series(result, index = list('ABCDEF'))
A     310
B    8000
C     320
D    2000
E     330
F    1000

相关问题 更多 >