首页 > 解决方案 > 添加带有条件的新列

问题描述

我需要通过添加更多列来管理数据框。我的数据头样本是

`Date` `Sentence` 
28 Jan      who.c   
30 Jan      house.a
02 Feb      eurolet.it

我需要添加另一列,Tp为每个链接分配一个值:

我写了以下内容:

conditions = [df['Sentence'].str.endswith(original), df['Sentence'].str.endswith(country)]
choices = [original, country]
# df['Tp'] = df.apply(lambda row: urlparse(row['Sentence']).netloc, axis = 1)
df['Tp'] = np.select(conditions, choices, default ='Unknown')
print(df)

在哪里

original= [('a', 'apartment'), ('b', 'bungalow'), ('c', 'church')]

country = [('UK', 'United Kingdom'), ('IT', 'Italy'), ('DE', 'Germany'), ('H', 'Holland'), ..., ('F', 'France'), ('S', 'Spain')]

country包含 50 多个元素。

你能告诉我如何解决吗?该列应添加到数据框中,然后添加到 csv 文件中。

谢谢

更新:

                      Sentences  \
    0                                      
    1                       who.c  
    2                  citta.me.it   
    3                    office.of
    4                   eurolet.eu   
    ..                               ...   
    995                    uilpa.ie   
    996                      fog.de

Original and country are from

list_country=np.array(country).tolist()
list_country_name=np.array(country_name).tolist()
flat_name_country = [item for sublist in list_country for item in sublist]
flat_country_name = [item for sublist in list_country_name for item in sublist] 

zip_domains=list(zip(flat_name_country, flat_country_name))

标签: pythonpandasdataframe

解决方案


你能把你的originalandcountry转换成 dict 吗?

original= [('a', 'apartment'), ('b', 'bungalow'), ('c', 'church')]
original = {x:y for x,y in original}
country = [('UK', 'United Kingdom'), ('IT', 'Italy'), ('DE', 'Germany'), ('H', 'Holland'), ..., ('F', 'France'), ('S', 'Spain')]
country = {x:y for x,y in country}

现在您可以执行与以下相同的任务:

df['Tp'] = df['Sentence'].apply(lambda sen : original.get( sen[-1], country.get(sen[-1], 'unknown') ) )

在您的代码中,您需要将元素的长度与 inconditions相同choices(以及扩展原始和国家/地区)


推荐阅读