Reputation: 80
I have a table of data that looks like this:
F M
f1 m1
f1 m2
f1 m3
f2 m1
f3 m1
f3 m2
and I need to add the third column made of objects of type str
. So the table should look like so:
F M B
f1 m1 'b1'
f1 m2 'b2'
f1 m3 'b3'
f2 m1 'b1'
f3 m1 'b1'
f3 m2 'b2'
What would be the right way to do this in pandas? There are similar questions but I couldn't find a similar task and I can't figure out how to construct this B column.
EDIT:
Sorry for not being clear enough. All the values in the table (f{i} and m{i}) are some strings.
Upvotes: 0
Views: 26
Reputation: 215107
Try groupby.cumcount
which essentially gives the row number for each F, and then you can concatenate the row number with a letter such as b
:
df['B'] = 'b'+df.groupby('F').cumcount().add(1).astype(str)
df
# F M B
#0 f1 m1 b1
#1 f1 m2 b2
#2 f1 m3 b3
#3 f2 m1 b1
#4 f3 m1 b1
#5 f3 m2 b2
Upvotes: 1