0

I am new to pandas, I am facing issue with replacing. So I am creating a function which replaces the values of column of a data frame based on the parameters. The condition is that it should replace all values of the column with only one value, as show below: Though I tried getting an error 'lenght didn't match'

    def replace(df,column,condition):
          for i in column:
              for j in condition:
                   df[i]=j
          return df
    column = ['A','C']
    condition = 11,34
    df
        A  B  C 
     0  12 5  1
     1  13 6  5
     2  14 7  7
    replace(df,column,condition)

my excepted output:

        A  B  C 
     0  11 5  34
     1  11 6  34
     2  11 7  34

2 Answers 2

1

Edit: I initially sugggested using apply but then realized that is not necessary since you are ignoring the existing values in the series. This is simpler and should serve your purposes.

Example:

import pandas as pd

data = [[12, 5, 1], [13, 5, 5], [14, 7, 7]]
df = pd.DataFrame(data, columns = ["A", "B", "C"])

def replace(df, columns, values):
    for one_column, one_value in zip(columns, values):
        df[one_column] = one_value

    return df

print(replace(df, ["A", "C"], [11, 34]))

Output:

    A  B   C
0  11  5  34
1  11  5  34
2  11  7  34
Sign up to request clarification or add additional context in comments.

2 Comments

now what does .apply(lambda _:one_value) do?
apply allows you to use the existing the contents of the series to compute new values. It is appropriate, for example, if you want to multiply each number in the series by 2. In your case, you don't care about the existing contents of the series, so apply is overkill.
1

Using key:value pair, convert condition and column into a dict, unpack and assign the values

df.assign(**dict(zip(column, condition)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.