简体   繁体   中英

How do I assign values to a new category using Pandas?

I have a variable, playlists, which I want to assign a categorical variable which takes values of "sleep" or "no_sleep", for each playlist. I have both lists with sleep / no sleep already assign as follows: Sleep: "Peaceful piano", "sleep", "Baby Sleep Aid", "White Noise"

No_sleep: "Dance Hits", "Dance Classics", "Massive Dance Hits", "Dance Party": ("Spotify", "37i9dQZF1DXaXB8fQg7xif")

How do I add the new variable to the pd.dataframe and assign the values? I imagine an if function for sleep and everything else is No_sleep, but not sure how to get started.

So the problem is to assign certain entries either no_sleep or sleep given the playlist name I am guessing.

Here is one way to do this:

df['sleep'] = "no_sleep"

sleep_idxs = np.array(df[df['playlist'].isin(sleep_playlists)].index)

df.iloc[sleep_idxs, 'sleep'] = "sleep"

Here you would need to have a list of those sleep playlist names ( sleep_playlists ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM