python How to add ordinals number to pandas dataframe

Viewed 98

I'm trying to automate a report by adding ordinal reference to items in a pandas dataframe or array

This is my data

 0 [John]
 1 [Jack, Tom]
 2 [Eric, Chris, Bob]

This is prefered output

0 [Primary oncall: John]
1 [Primary oncall: Jack, Secondary oncall: Tom]
2 [Primary oncall: Eric, Secondary oncall: Chris, Third oncall: Bob]

I've tried without any luck to implement the following script https://rosettacode.org/wiki/Number_names#Python

Can someone please point me on how to accomplish this Thank you

1 Answers

This is a crude solution, that requires you create a mapping for each count of each list in the column :

df = pd.DataFrame({"header": [["John"], 
                              ["Jack", "Tom"], 
                              ["Eric", "Chris", "Bob"]]}
                   )
df

# you have to create a mapping to match the length of each sublist
mapping = {0: "Primary", 1: "Secondary", 2: "Third"}

df['header'] = [[", ".join(f"{mapping[num]} oncall: {entry[num]}" 
                        for num in range(len(entry)))]
             for entry in df.header]

Hopefully the code above points you in the right direction

Related