0

I am trying to write some code in python that will split the string in a cell if the cell value contains a certain word.

I have made a sample dataframe to explain the challenge I'm facing.

d = {'Message': [1, 2,3], 'Details': ['I WANT IT ALL', 'HELLO WORLD','NOPE IT IS NOT CORRECT']}
df = pd.DataFrame(data=d)
df

I cant figure out the rest of this code.

 d['New Column'] = pd.np.where(d['Details'].str.contains("WANT"),

If column contains "want" the 'New Column' value = 'want all' ELSE other.

Thank you in advance community.

1 Answers1

1

here you go.

def get_left(value: str) -> str:
    return df.query("Details.str.contains(@value)").at[0, "Details"].split(value)[0]


df["New Column"] = np.where(df["Details"].str.contains("WANT"), get_left("WANT"), "other")
print(df)

   Message                 Details New Column
0        1           I WANT IT ALL         I 
1        2             HELLO WORLD      other
2        3  NOPE IT IS NOT CORRECT      other
Jason Baker
  • 3,170
  • 2
  • 12
  • 15
  • Thanks for the reply Jason. However, this was just an example. I really need to figure out how to use the split method on this. Ideally splitting the text left of a delimiter. – Shane Nicholson Oct 23 '22 at 07:35
  • I need to get the text to the left of a string if a condition is met. – Shane Nicholson Oct 23 '22 at 08:33
  • See edit. if this still doesn't fit your criteria update the question to explain better, also adding an expected output helps. – Jason Baker Oct 23 '22 at 15:09
  • Hey Jason, defo on the right page but I am still getting an error. Replicating this exact code gives me the following error : 'Series' objects are mutable, thus they cannot be hashed. Python should not be this difficult , surely :( – Shane Nicholson Oct 23 '22 at 20:16