4
\$\begingroup\$

i'm using a dataframe full of headers/field names to develop a schema and I need unique values for each header - but each header should be represented. I want to loop though the dataframe list of fields and the second time I come across a field name, I want to add an ever increasing number to it. The order is important.

e.g.

headers['name'] =pd.DataFrame['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit']

I need the output to be:

name      | name+count
vegetable | vegetable
fruit     | fruit
meat      | meat
dairy     | dairy
meat      | meat1
fruit     | fruit1
fruit     | fruit2
for header in headers['names']:
       row = headers.loc[headers['names'] == header].index
       if len(row) > 1:
           for i in range(2, len(row)):
               headers['name+count'][row[i]] = headers['names'][row[i]] + str(i-1)
               print(headers['name+count'][row[i]])
\$\endgroup\$
  • \$\begingroup\$ Your descriptions makes no sense to me? can you rephrase it? Also is the code working as you want, so it can be reviewed? \$\endgroup\$ – 422_unprocessable_entity Mar 4 at 14:54
  • \$\begingroup\$ @422_unprocessable_entity My edit which has been overwritten codereview.stackexchange.com/revisions/214708/2 \$\endgroup\$ – REdim.Learning Mar 4 at 15:07
  • 1
    \$\begingroup\$ That looks like unlucky timing, since the timestamps are so close to each other. As OP you should be able to rollback to your revision 2 using the revisions page for this post. After that just apply the parts of the edit by @200_success you agree with (it seems like most you already did yourself, such as the code being properly marked as code). \$\endgroup\$ – Graipher Mar 4 at 16:20
4
\$\begingroup\$

You can group by the name and then append an increasing number to it:

import pandas as pd

def add_count(x):
    return x + ([""] + list(map(str, range(1, len(x)))))

df = pd.DataFrame(['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit'],
                  columns=["name"])
x = df.groupby("name", as_index=False)["name"].apply(add_count)
df["name2"] = x.reset_index(level=0, drop=True)
print(df)
#         name       name2
# 0  vegetable   vegetable
# 1      fruit       fruit
# 2       meat        meat
# 3      dairy       dairy
# 4       meat       meat1
# 5      fruit      fruit1
# 6      fruit      fruit2

This avoids manually iterating over rows or columns, something that is usually a good thing when dealing with pandas dataframes.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.