Search code examples
pythonpandasdataframe

Replace values in pandas column


I have a df:

building building:use
industrial None
office None
police None
house None
church residential
... ...

How would I replace building with building:use if and only if the building:use is residential?

A new df would be appreciated.


Solution

  • I created df2 as you specified wanting a new df.

    df2 = df.copy()
    df_res = df2[df2['building:use'] == 'residential']
    df2.loc[df_res.index, 'building'] = df_res['building:use'] 
    

    For reference, your example dataset

    import pandas as pd
    
    df = pd.DataFrame(
        {
            "building": ["industrial", "office", "police", "house", "church"],
            "building:use": [None, None, None, None, "residential"],
        }
    )