Home > Enterprise >  How to replicate dataframe rows based on condition
How to replicate dataframe rows based on condition

Time:12-02

I have input dataframe df1 like this:

url_asia_us_emea
https://asia/image
https://asia/location
https://asia/video

I want to replicate the rows in df1 with changes in region based on the column names.Lets say for this example , I need the below output as all three regions are in the column name

url_asia_us_emea
https://asia/image
https://asia/location
https://asia/video
https://us/image
https://us/location
https://us/video
https://emea/image
https://emea/location
https://emea/video

CodePudding user response:

You could do something like this:

list_strings = [ 'us', 'ema', 'fr']
df_orig =pd.read_csv("ack.csv", sep=";")

which is

    url
0     https://asia/image
1  https://asia/location
2     https://asia/video

and then

d = []
for element in list_strings:
    df =pd.read_csv("ack.csv", sep=";")
    df['url'] = df['url'].replace({'asia': str(element)}, regex=True)
    d.append(df)
    
df = pd.concat(d)
DF = pd.concat([df,df_orig])

which results in

index                    url
0             https://us/image
1         https://us/location
2             https://us/video
3            https://ema/image
4         https://ema/location
5            https://ema/video
6             https://fr/image
7          https://fr/location
8             https://fr/video
9            https://asia/image
10        https://asia/location
11           https://asia/video
​
  • Related