Search code examples
pythonstringlistdataframeposition

How to check if the column name is at the last or in the front of a string (python)?


I am new to pandas. I have an issue with knowing where the column is in last or first inside a string. For suppose I have a string str = "000*999bikes" where the bikes is a column name of df, now I want to check the position of the column whether it is in the first or last

My code:

str = "000*999bikes"
df =
  bikes cars
0  12    23
1  34    67
3  56    90

Now the column name bikes is in last of a string. How to know if it is in the last using if condition?


Solution

  • If you just want the number beside the column name, you can use the following code to check for each column.

    import pandas as pd
    
    df = pd.DataFrame([[1,2],[2,2]],columns=['bikes','cars'])
    
    strings = ["cars000*999","000*999bikes"]
    
    for s in strings:
        for col in df.columns:
            if s.startswith(col):
                print(col, s[len(col) + 1])
            if s.endswith(col):
                print(col, s[-len(col) - 1])
    

    Output:

    cars 0
    bikes 9
    

    If your strings are in the dataframe then you could do this with pandas str operations instead of loops.