Skip to main content
added 417 characters in body
Source Link
user52601
user52601

Try:

# Create an example dataframe
df = pd.DataFrame({"genres":["Fantasy|Sci-Fi",
                "Action|Adventure|Fantasy",
                "Thriller",
                "Action|Adventure|Thriller|bbv","Action","Action|Adventure|thriller"]})

# Get a dataframe with as many columns as there are genres
df = df.genres.str.get_dummies(sep = "|")

# Get the genres as values
df = df.multiply(df.columns)

# Rename the columns to have the genre id
df.columns = ["genre_" + str(x) for x in range(len(df.columns))]

Input:

enter image description here

Output:

enter image description here

EDIT:

you can simply use pandas assign method:

df.assign(genre1= df.genres.str.split("|", expand = True).iloc[:,:1],
          genre2 = df.genres.str.split("|", expand = True).iloc[:,1:2])

*Output:

enter image description here

Try:

# Create an example dataframe
df = pd.DataFrame({"genres":["Fantasy|Sci-Fi",
                "Action|Adventure|Fantasy",
                "Thriller",
                "Action|Adventure|Thriller|bbv","Action","Action|Adventure|thriller"]})

# Get a dataframe with as many columns as there are genres
df = df.genres.str.get_dummies(sep = "|")

# Get the genres as values
df = df.multiply(df.columns)

# Rename the columns to have the genre id
df.columns = ["genre_" + str(x) for x in range(len(df.columns))]

Input:

enter image description here

Output:

enter image description here

Try:

# Create an example dataframe
df = pd.DataFrame({"genres":["Fantasy|Sci-Fi",
                "Action|Adventure|Fantasy",
                "Thriller",
                "Action|Adventure|Thriller|bbv","Action","Action|Adventure|thriller"]})

# Get a dataframe with as many columns as there are genres
df = df.genres.str.get_dummies(sep = "|")

# Get the genres as values
df = df.multiply(df.columns)

# Rename the columns to have the genre id
df.columns = ["genre_" + str(x) for x in range(len(df.columns))]

Input:

enter image description here

Output:

enter image description here

EDIT:

you can simply use pandas assign method:

df.assign(genre1= df.genres.str.split("|", expand = True).iloc[:,:1],
          genre2 = df.genres.str.split("|", expand = True).iloc[:,1:2])

*Output:

enter image description here

Source Link
user52601
user52601

Try:

# Create an example dataframe
df = pd.DataFrame({"genres":["Fantasy|Sci-Fi",
                "Action|Adventure|Fantasy",
                "Thriller",
                "Action|Adventure|Thriller|bbv","Action","Action|Adventure|thriller"]})

# Get a dataframe with as many columns as there are genres
df = df.genres.str.get_dummies(sep = "|")

# Get the genres as values
df = df.multiply(df.columns)

# Rename the columns to have the genre id
df.columns = ["genre_" + str(x) for x in range(len(df.columns))]

Input:

enter image description here

Output:

enter image description here