簡體   English   中英

將 pandas dataframe 列拆分為多個並遍歷它

[英]Split a pandas dataframe column into multiple and iterate through it

我正在嘗試找一位具有匹配 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 簡單地表示藝術家是不是搖滾/嘻哈/陷阱等。 使用屬性的二進制表示。

這是當前的 dataframe

在此處輸入圖像描述

獲取我的數據框並將類型拆分為單獨的,以便我可以轉換為 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
----------------------------------------------------------------------------------------------------

每個流派都用 | 分隔所以我們只需要在 | 上調用拆分 function。

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

首先將df復制到df中。

artists_with_genres = df.copy(deep=True)

然后遍歷 df,然后是 append 藝術家流派作為 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)

嘗試使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM