Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe replace part of string with value from another column

I having replace issue while I try to replace a string with value from another column. I want to replace 'Length' with df['Length'].

df["Length"]= df["Length"].replace('Length', df['Length'], regex = True)

Below is my data

Input:
**Formula**  **Length**
Length           5
Length+1.5       6
Length-2.5       5
Length           4
5                5

Expected Output:
**Formula**  **Length**
5                5
6+1.5            6
5-2.5            5
4                4
5                5

However, with the code I used above, it will replace my entire cell instead of Length only. I getting below output: I found it was due to df['column'] is used, if I used any other string the behind offset (-1.5) will not get replaced.

**Formula**  **Length**
5                5
6                6
5                5
4                4
5                5

May I know is there any replace method for values from other columns?

Thank you.

like image 865
Js _ lfzr Avatar asked Jul 20 '20 06:07

Js _ lfzr


People also ask

How to replace values in pandas Dataframe?

Depending on your needs, you may use either of the following methods to replace values in Pandas DataFrame: (1) Replace a single value with a new value for an individual DataFrame column: (2) Replace multiple values with a new value for an individual DataFrame column:

How do I replace a character in a Dataframe?

(1) Replace character/s under a single DataFrame column: df ['column name'] = df ['column name'].str.replace ('old character','new character') (2) Replace character/s under the entire DataFrame: df = df.replace ('old character','new character', regex=True)

How to replace values from another Dataframe when different indices are used?

So to replace values from another DataFrame when different indices we can use: Now the values are correctly set: You can use Pandas merge function in order to get values and columns from another DataFrame. For this purpose you will need to have reference column between both DataFrames or use the index.

How to replace a substring of a column in pandas python?

Replace a substring of a column in pandas python can be done by replace () funtion. Let’s see how to Replace a substring with another substring in pandas Replace a pattern of substring with another substring using regular expression


1 Answers

If want replace by another column is necessary use DataFrame.apply:

df["Formula"]= df.apply(lambda x: x['Formula'].replace('Length', str(x['Length'])), axis=1)
print (df)
  Formula  Length
0       5       5
1   6+1.5       6
2   5-2.5       5
3       4       4
4       5       5

Or list comprehension:

df["Formula"]= [x.replace('Length', str(y)) for x, y  in df[['Formula','Length']].to_numpy()]
like image 199
jezrael Avatar answered Oct 13 '22 21:10

jezrael