1

What I have:

df = pd.DataFrame(data = ["version11.11","version2.2","version3"], columns=["software_version"])


  Index software_version
    0   version11.11
    1   version2.2
    2   version3

What I am trying to do:

Is to detect the type of the second last character in the dataframe column called software_version and create a new column in the dataframe based on that condition.

If the second last character is a digit or an alphabet, extract the whole name without the last alpha/digital. Such as version11.11 becomes version11.1 OR version3 becomes version. elif, its a decimal place then extract til before the decimal place, version2.2 becomes version2

Output Should be:

  Index software_version  main_software
    0   version11.11     version11.1
    1   version2.2       version2
    2   version3         version

What I did so far:

How can I cleanly add the column above main_software ?

import pandas as pd

df = pd.DataFrame(data = ["version11.11","version2.2","version3"], columns=["software_version"])

for name in df.software_version:
    if name[-2].isalnum():
        print(name[:-1])

    elif name[-2] == ".":
        print(name[:-2])

    else :
        print("!Alphanum-dot")

1 Answer 1

1

You can first define a function that makes the necessary changes on the string.

def GetMainSoftware(string):
    new_string=string[:-1] #first remove the last character
    if(new_string[-1]=="."): #if "." is present, remove that too
        return new_string[:-1]
    else:
        return new_string

And then use apply on the dataframe to create a new column with these specifics.

df["main_software"]=df.apply(lambda row: GetMainSoftware(row["software_version"]),axis=1)

df will now be :

  software_version main_software
0     version11.11   version11.1
1       version2.2      version2
2         version3       version
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.