M
M
MR88082018-10-15 15:43:59
Python
MR8808, 2018-10-15 15:43:59

How to replace data in Data frame?

I have two csv files. In the first - just a column with the names of objects (old names). The second one has two columns: 1st column - old names, 2nd column - new names of objects.
It is necessary to make sure that the names in the first file are changed to new ones (those in the second column). And if this object is not in the second file, then it (the object) has retained its old name. It turns out you need to do something like VLOOKUP in excel. Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artgor, 2018-10-16
@Artgor

Let's say there are 2 files:

df1 = pd.DataFrame({'name': ['a', 'b', 'c']})
df2 = pd.DataFrame({'old_name': ['a', 'b'], 'new_name': ['a1', 'b1']})

Here's what you can do:
df3 = pd.merge(df1, df2, left_on='name', right_on='old_name',  how='left')
df3.loc[df3['new_name'].isnull(), 'new_name'] = df3.loc[df3['new_name'].isnull(), 'name']

First, we join by the old name, then in the lines where there is no new name, we replace the missing values ​​with the old ones. df3['new_name'] - the column with the resulting values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question