简体   繁体   English

如何使用 Pandas 将值分配给新类别?

[英]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.我有一个变量,播放列表,我想为每个播放列表分配一个分类变量,该变量采用“sleep”或“no_sleep”的值。 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") 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?如何将新变量添加到 pd.dataframe 并分配值? I imagine an if function for sleep and everything else is No_sleep, but not sure how to get started.我想如果 function 用于睡眠,其他一切都是 No_sleep,但不知道如何开始。

So the problem is to assign certain entries either no_sleep or sleep given the playlist name I am guessing.所以问题是根据我猜的播放列表名称分配某些条目no_sleepsleep

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 ).在这里,您需要列出这些睡眠播放列表名称( sleep_playlists )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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