簡體   English   中英

如何為列表中的每個元素創建不同的列?

[英]How to make different columns for each elements in a list?

我有一個 pandas dataframe 列,其中包含字符串列表(長度不同),如下所示: df['category']

category                                                                           | ...
---------
['Grocery & Gourmet Food', 'Cooking & Baking', 'Lard & Shortening', 'Shortening']  | ...
['Grocery & Gourmet Food', 'Candy & Chocolate', 'Mints']                           | ...
['Grocery & Gourmet Food', 'Soups, Stocks & Broths', 'Broths', 'Chicken']          | ...

現在,我想為列表中的每個字符串元素將此類別列分成不同的列。 可以使用 pandas 嗎? 我將如何處理列名?

我已經完成了這個問題的答案,但不同的是我的列表長度並不總是相同。

我預期的 output 將如下所示:

category_1             | category_2       |  category_n  | other_columns 
------------------------------------------------------------------
Grocery & Gourmet Food | Cooking & Baking | Lard & Shortening | ...
...                    | ...              | ...               | ...

我會做這樣的事情:

df2 = pd.DataFrame(df['category'].to_list(), columns=[f"category_{i+1}" for i in range(len(df['category'].max()))])
df = pd.concat([df.drop('category', axis=1), df2], axis=1)

Output:

               category_1              category_2         category_3  \
0  Grocery & Gourmet Food        Cooking & Baking  Lard & Shortening   
1  Grocery & Gourmet Food       Candy & Chocolate              Mints   
2  Grocery & Gourmet Food  Soups, Stocks & Broths             Broths   

   category_4  
0  Shortening  
1        None  
2     Chicken 

編輯:

正如@mozway建議的那樣,最好使用默認名稱創建列,然后更新它們:

df2 = pd.DataFrame(df['category'].to_list())
df2.columns = df2.columns.map(lambda x: f'category_{x+1}')
df = pd.concat([df.drop('category', axis=1), df2], axis=1)

暫無
暫無

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

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