I'd like to combine files A and B from Python.

Asked 2 years ago, Updated 2 years ago, 18 views

My knowledge of Python and Linux is shallow, so I have limitations in writing. The file A is

It has this format

B file is

What I'm curious about here is that I want to merge the rows with only the common numbers in the two different files I tried using a dictionary, but it didn't work because it didn't fit.

f = open("test.txt", "r")
read = f.read()
split = read.split()
print(split)

Even if I split it like this, I don't know how to pull out a line, but I don't know how to pull out the third number. It's harder than I thought. It would be very helpful for me just to tell me which function to use.

python

2022-09-22 19:25

1 Answers

Using Pandas is the best way.

df1 = pd.read_csv('file1.txt', header=None, names=['A', 'B', 'value'])
df2 = pd.read_csv('file2.txt', header=None, names=['value', 'AAA', 'BBB'])

df3 = pd.merge(df1, df2)

The join method can be controlled by the how factor of merge, and if you want to join based on a column with a different name, use a factor such as on. Read the documentation for detailed instructions.


2022-09-22 19:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.