1

I have a third column in my data frame where I want to be able to create a fourth column that looks almost the same, except it has no double quotes and there is a 'user/' prefix before each ID in the list. Also, sometimes it is just a single ID vs. list of IDs (as shown in example DF).

original

col1   col2     col3 
01      01     "ID278, ID289"

02      02     "ID275"

desired

col1   col2     col3                col4
01      01     "ID278, ID289"     user/ID278, user/ID289

02      02     "ID275"            user/ID275

1
  • I added a method that deals with rows that are empty, either filled with np.nan or empty strings ''. Commented Jul 19, 2022 at 5:07

3 Answers 3

1

Given:

   col1  col2            col3
0   1.0   1.0  "ID278, ID289"
1   2.0   2.0         "ID275"
2   2.0   1.0             NaN

Doing:

df['col4'] = (df.col3.str.strip('"')  # Remove " from both ends.
                     .str.split(', ') # Split into lists on ', '.
                     .apply(lambda x: ['user/' + i for i in x if i] # Apply this list comprehension,
                                       if isinstance(x, list)  # If it's a list.
                                       else x)
                     .str.join(', ')) # Join them back together.
print(df)

Output:

   col1  col2            col3                    col4
0   1.0   1.0  "ID278, ID289"  user/ID278, user/ID289
1   2.0   2.0         "ID275"              user/ID275
2   2.0   1.0             NaN                     NaN
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a solution that takes both the double quotes and ID lists into account:

# remove the double quotes
df['col4'] = df['col3'].str.strip('"')
# split the string, add prefix user/, and then join
df['col4'] = df['col4'].apply(lambda x: ', '.join(f"user/{userId}" for userId in x.split(', ')))

1 Comment

I also forgot to mention there are some rows that are empty in col 3, would you please revise the code for this aspect?
0

You can use .apply() function:

def function(x):
    if not x:
        return ""
    
    elements = x.split(", ")
    out = list()
    
    for i in elements:
        out.append(f"user/{i}")
        
    return ", ".join(out)

df["col4"] = df.col3.apply(function)

That returns:

col1  col2  col3          col4
1     1     ID278, ID289  user/ID278, user/ID289
2     2     ID275         user/ID275
3     3 

2 Comments

I also forgot to mention there are some rows that are empty in col 3, would you please revise the code for this aspect?
I updated the function, it will make that the empty rows return a empty string for the new column

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.