python_infant
python_infant

Reputation: 57

Setting String Values of a Pandas Column with Indices

I am trying to generate a new column in my dataframe where a string is assigned for different index values. I'm not exactly skilled enough to do it with a loop, so I tried subsetting and indexing to see if I could make my life easier.

df['event_type'] = []

A = df[df['flags'].isin(['A'])].index
B= df[df['flags'].isin(['B'])].index
C = df[df['flags'].isin(['B'])].index


df.loc[A, 'event_type'] = 'Condition One'
df.loc[B, 'event_type'] = 'Condition Two'
df.loc[C, 'event_type'] = 'Condition Three'

I've gotten the length of values does not match length of index and Index.name must be a hashable type errors several times now. I just want to assign these strings to these indices in the new columns, all the other values in the column can be Nan.

Upvotes: 0

Views: 133

Answers (1)

sushanth
sushanth

Reputation: 8302

You can use Series.map,

df['event_type'] = df.flags.fillna('').map(
    {"A": "Condition One", "B": "Condition Two", "C": "Condition Three"}
)

Upvotes: 1

Related Questions