-1

Trying to make a custom string out of a column. The 'ENTITY' column is either 6 numbers (ex. 184025.0) or 5 numbers (ex. 58063.0). The third to last number before the decimal is always a zero, no matter how many numbers there are. The format should be 000-00, first 3 numbers, dash (which replaces the 0), and the last 2 numbers before the decimal. If the 'ENTITY' only has 5 numbers, a leading zero also needs to be added.

Using the examples above the return values should be:

184025.0 = "184-25"

58063.0 = "058-63"

I tried this but keep getting the original object returned.

cost_centers['length'] = cost_centers['ENTITY'].astype(str)
cost_centers['len'] = cost_centers['length'].str.len()

if cost_centers['len'].equals(7):
    cost_centers['COST CENTER'] = '0' + cost_centers['length'][:2] + "-" + cost_centers['length'][2:4]
elif cost_centers['len'].equals(8):
    cost_centers['COST CENTER'] =  cost_centers['length'].str[:3] + "-" + cost_centers['length'].str[3:]
else:
    cost_centers['COST CENTER'] = cost_centers['length']
Ceci V
  • 1
  • 1
  • 1
    What is your question? – Code-Apprentice Jul 18 '23 at 21:40
  • Side note: You don't need to compare with boolean values if the result of the expression is already a boolean. In other words, just do `if cost_centers['len'].equals(7):`, for example. Better yet, use `==` to compare: `if cost_centers['len'] == 7:`. And better yet, use pandas broadcasting to help: `cost_centers[cost_centers['len'] == 7]['COST CENTER'] = ...` – Code-Apprentice Jul 18 '23 at 21:42
  • It looks like you misunderstood what `.equals()` does. It compares the whole object (Series) not the values inside it. However, if you did compare the values, with `.eq()` for example, you'd get `ValueError: The truth value of a Series is ambiguous` in the if-statements. I guess you forgot to use a loop, but like Beny answered, there are better ways to do this. BTW, the results are strings (dtype object), not floats. – wjandrea Jul 18 '23 at 21:53
  • BTW, welcome to Stack Overflow! Please take the [tour] and read [ask]. Also if it helps for future questions: [How to make good reproducible pandas examples](/q/20109391/4518341) – wjandrea Jul 18 '23 at 21:54

1 Answers1

1

Let us try

s = pd.Series([184025.0,58063.0])
out = s.astype(int).astype(str).str.zfill(6).str.slice_replace(3,4,'-')
out
Out[23]: 
0    184-25
1    058-63
dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234