Python 根据另一列中的输入创建具有特定值的列

Python 根据另一列中的输入创建具有特定值的列,python,pandas,csv,Python,Pandas,Csv,在我的csv文件中,我有一列“category”,其中我需要为每个类别设置一个垂直方向,并将值保存在新的附加列中。我知道如何读取csv并将数据帧保存到新文件中,包括在Pandas中创建新列。然而,我需要一些关于我的场景逻辑的帮助 my.csv: id category 1 auto,auto.car_dealers 2 hotelstravel,hotelstravel.hotels 3 shopping,shopping.homeandgarden,sh

在我的csv文件中,我有一列“category”,其中我需要为每个类别设置一个垂直方向,并将值保存在新的附加列中。我知道如何读取csv并将数据帧保存到新文件中,包括在Pandas中创建新列。然而,我需要一些关于我的场景逻辑的帮助

my.csv:

id            category
1    auto,auto.car_dealers
2    hotelstravel,hotelstravel.hotels
3    shopping,shopping.homeandgarden,shopping.homeandgarden.appliances
4    financialservices,financialservices.insurance
5    
6    realestate
7    pets,pets.petservices,pets.petservices.petinsurance
8    homeservices,homeservices.windowsinstallation
9    professional
我需要应用的规则: 1.如果类别列没有值,则设置垂直列=其他 2.如果类别列有值,则检查值是否为单个单词,然后根据值设置为垂直。如果自动,则设置为自动;如果hotelstravel,则设置为Travel等。 3.如果值有多个单词,则在第一个逗号之前取该单词,并根据类别设置垂直值。如果自动,则设置为自动;如果hotelstravel,则设置为Travel等

预期输出.csv:

id            category                                                       vertical 
1    auto,auto.car_dealers                                                   Automotive
2    hotelstravel,hotelstravel.hotels                                        Travel
3    shopping,shopping.homeandgarden,shopping.homeandgarden.appliances       Retail
4    financialservices,financialservices.insurance                           Financial
5                                                                            Other
6    realestate                                                              Real Estate
7    pets,pets.petservices,pets.petservices.petinsurance                     Pet Services
8    homeservices,homeservices.windowsinstallation                           Home Services
9    professional                                                            Professional Services
到目前为止,我的代码是:

import pandas as pd
df = pd.read_csv('path/to/my.csv')

#do something here and then something like
df.loc[df['category'] == 'auto', 'vertical'] = 'Automotive'

df.to_csv('path/to/output.csv', index=False)

对此,任何帮助都将不胜感激。提前谢谢你

您可能需要遍历category列并对值执行检查。您可以使用以下内容():

而且,由于您希望更改值,即“hotelstravel”更改为“Travel”,因此可能需要设置一个字典,以类别名称作为键,以垂直名称作为值,以便快速转换

for index, row in df.iterrows():
    if (row['Category'].is_a_list()):
        tokens = row['Category'].split()
        row['Vertical'] = tokens[0]
    else:
         ....