1

I have a dataset

dt | ticker_like | text
12:16:17 | Ab | hello ab nice to meet you
12:16:18 | hey, you | hey I will be happy to meet you

I want to write a code depending on how many comma separated words are in the ticker_like, I want to duplicate them like this

dt | ticker_like | text
12:16:17 | Ab | hello ab nice to meet you
12:16:18 | hey | hey I will be happy to meet you
12:16:18 | you | hey I will be happy to meet you

2 Answers 2

1

You can use .explode:

df["ticker_like"] = df["ticker_like"].apply(
    lambda x: list(map(str.strip, x.split(",")))
)
df = df.explode("ticker_like").reset_index(drop=True)
print(df)

Prints:

         dt ticker_like                             text
0  12:16:17          Ab        hello ab nice to meet you
1  12:16:18         hey  hey I will be happy to meet you
2  12:16:18         you  hey I will be happy to meet you
Sign up to request clarification or add additional context in comments.

Comments

0
# Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import pandas as pd
data = {'dt':['12:16:17', '12:16:18'],
        'ticker_like':['Ab','Hey,you'],
        'text':['hello ab nice to meet you','hey I will be happy to meet you']
}
 
# Create DataFrame
df = pd.DataFrame(data)
print(df)
for index, row in df.iterrows():
    if(',' in row['ticker_like']):
        values= row['ticker_like'].split(',')
        df['ticker_like'].replace(row['ticker_like'],values[0], inplace=True)
        df.loc[len(df.index)] = [row['dt'],values[1],row['text']] 
# Print the output.
print(df)

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.