Skip to content Skip to sidebar Skip to footer

How To Set A Pandas Dataframes Column Value Based On A Condition Applied To Another Column

I have a dataframe to which I want to add another column and that depends on the values based on what other column in that particular cell. I keep getting TypeError: string indices

Solution 1:

The following worked for me:

df.loc[df['ID'].str.contains('1'), 'Name'] = 'n0, n1'

Basically you need to use .loc[row_index, col_index] = val to modify an existing dataframe.

Using df[row_index][col_index] just creates a copy of the value I believe.

This is also assuming you've already defined the column:

df['Name'] = pd.Series()

Post a Comment for "How To Set A Pandas Dataframes Column Value Based On A Condition Applied To Another Column"