【问题标题】:Split a pandas dataframe column into multiple and iterate through it将 pandas 数据框列拆分为多个并遍历它
【发布时间】:2020-09-23 20:13:32
【问题描述】:

我正在尝试找一位具有匹配 id 的艺术家来制作跨越各种单数到流派组合的音乐。

这就是我想做的事情

Artist | Id | Genre                | Jazz | Blues | Rock | Trap | Rap | Hip-Hop | Pop | Rb  |
----------------------------------------------------------------------------------------------------
Bob    | 1  | [Jazz, Blues]        |   1  |   1   |   0  |   0  |   0 |   0     |  0  |   0
----------------------------------------------------------------------------------------------------
Fred   | 2  | [Rock,Jazz]          |   1  |   0   |   1  |   0  |   0 |   0     | 0   |   0
----------------------------------------------------------------------------------------------------
Jeff   | 3  | [Trap, Rap, Hip-Hop] |   0  |   0   |   0  |   1  |   1 |   1     | 0   |   0
----------------------------------------------------------------------------------------------------
Amy    | 4  | [Pop, Rock, Jazz]    |   1  |   0   |   1  |   0  |   0 |   0     | 1   |   0
----------------------------------------------------------------------------------------------------
Mary   | 5  | [Hip-Hop, Jazz, Rb]  |   1  |   0   |   0  |   0  |   0 |   1     | 0   |   1
----------------------------------------------------------------------------------------------------

这是我得到的错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-7a4ed81e14d7> in <module>
     11 for index, row in artist_df.iterrows():
     12     x.append(index)
---> 13     for i in row['genre']:
     14         artists_with_genres.at[index, genre] = 1
     15 

TypeError: 'float' object is not iterable

这些(艺术家)流派是我将用来帮助确定相似艺术家的属性,结合其他因素(如年份、歌曲或人口统计数据)。

我正在创建和迭代的新列将指定艺术家是否属于某个流派。用 1/0 简单地表示艺术家是不是摇滚/嘻哈/陷阱等。使用属性的二进制表示。

这是当前数据帧

获取我的数据框并将类型拆分为单独的类型,以便我可以转换为 1/0 二进制表示。

我需要为索引设置流派吗?

第一个这样的数据帧

Artist | Id | Genre               |
--------------------------------------
Bob    |  1 | Jazz | Blues
--------------------------------------
Fred   |  2 | Rock | Jazz
--------------------------------------
Jeff   |  3 | Trap | Rap | Hip-Hop
--------------------------------------
Amy    |  4 | Pop | Rock | Jazz
--------------------------------------
Mary   |  5 | Hip-Hop | Jazz | Rb

这就是我想做的事情

Artist | Id | Genre                | Jazz | Blues | Rock | Trap | Rap | Hip-Hop | Pop | Rb  |
----------------------------------------------------------------------------------------------------
Bob    | 1  | [Jazz, Blues]        |   1  |   1   |   0  |   0  |   0 |   0     |  0  |   0
----------------------------------------------------------------------------------------------------
Fred   | 2  | [Rock,Jazz]          |   1  |   0   |   1  |   0  |   0 |   0     | 0   |   0
----------------------------------------------------------------------------------------------------
Jeff   | 3  | [Trap, Rap, Hip-Hop] |   0  |   0   |   0  |   1  |   1 |   1     | 0   |   0
----------------------------------------------------------------------------------------------------
Amy    | 4  | [Pop, Rock, Jazz]    |   1  |   0   |   1  |   0  |   0 |   0     | 1   |   0
----------------------------------------------------------------------------------------------------
Mary   | 5  | [Hip-Hop, Jazz, Rb]  |   1  |   0   |   0  |   0  |   0 |   1     | 0   |   1
----------------------------------------------------------------------------------------------------

每个流派都用 | 分隔所以我们只需要在 | 上调用 split 函数。

[![artist_df\['genres'\] = artist_df.genres.str.split('|')
artist_df.head()][1]][1]

首先将 df 复制到 df 中。

artists_with_genres = df.copy(deep=True)

然后遍历 df,然后将艺术家流派附加为 1 或 0 列。

如果该列包含当前索引的流派中的艺术家,则为 1,否则为 0。

x = []

for index, row in artist_df.iterrows():
   x.append(index)
   for genre in row['genres']:
       artists_with_genres.at[index, genre] = 1

**Confirm that every row has been iterated and acted upon.**

print(len(x) == len(artist_df))

artists_with_genres.head(30)

用 0 填充 NaN 值以表明艺术家没有该列的流派。

artists_with_genres = artists_with_genres.fillna(0)
artists_with_genres.head(3)

【问题讨论】:

  • 您看过一种热门编码吗? pd.get_dummies() 可能只是给你你需要的东西。
  • 不,我从未听说过使用 pd.get_dummies() 进行热编码。但我会调查一下
  • 正在尝试但遇到了浮动问题。
  • 使用 artist_df['genre'] = artist_df['genre'].astype(str)

标签: python pandas loops dataframe


【解决方案1】:

get_dummies试试这个:

df['Genre'] = df['Genre'].str.split('|')
dfx = pd.get_dummies(pd.DataFrame(df['Genre'].tolist()).stack()).sum(level=0)
df = pd.concat([df, dfx], axis=1).drop(columns=['Genre'])
print(df)

  Artist  Id  Blues  Hip-Hop  Jazz  Pop  Rap  Rb  Rock  Trap
0    Bob   1      1        0     1    0    0   0     0     0
1   Fred   2      0        0     1    0    0   0     1     0
2   Jeff   3      0        1     0    0    1   0     0     1
3    Amy   4      0        0     1    1    0   0     1     0
4   Mary   5      0        1     1    0    0   1     0     0

详细解释看这里->Pandas column of lists to separate columns

【讨论】:

  • 得到这个错误'AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas'
  • 我认为这是因为它是 float64 artist_df['genre'].dtypes dtype('float64')
  • 流派如何成为浮动?
  • 不知道我是如何清理数据的。我能够转换为 obj
  • df3['genre'] = df3['genre'].astype(str)
猜你喜欢
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 2016-10-13
  • 2017-08-29
  • 1970-01-01
  • 2016-06-24
  • 2018-11-17
  • 1970-01-01
相关资源
最近更新 更多