python - 添加带有条件的新列
问题描述
我需要通过添加更多列来管理数据框。我的数据头样本是
`Date` `Sentence`
28 Jan who.c
30 Jan house.a
02 Feb eurolet.it
我需要添加另一列,Tp
为每个链接分配一个值:
- 如果一个句子以
a
then assign结尾apartment
;如果它以b
then assignbungalow
等结尾,如图所示original
; 如果一个句子以
UK
then assign结尾United Kingdom
;如果它以IT
then assign结尾Italy
,依此类推。值来自country
。我会期待这样的事情:日期句子 Tp 1 月 28 日 who.c 教堂 1 月 30 日 house.a 公寓 2 月 2 日 eurolet.it。意大利
我写了以下内容:
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))
解决方案
你能把你的original
andcountry
转换成 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
(以及扩展原始和国家/地区)
推荐阅读
- ruby - 如何使用 dig 方法获取嵌套属性
- r - 用 R dyplyr 有条件地重新编码/替换变量?
- angular - Http 请求仅在发布 Android 构建 APK 时失败,但在调试时有效
- python - 检查输入时出错:预期 embedding_1_input 有 2 维,但得到了形状为 () 的数组
- html - 我遇到了悬停效果的问题
- java - Java - 如何将 URL 转换为 Files.lines() 的 PATH
- docker - 从 ssh 退出时,在分离的 docker 容器中运行的命令是否继续运行?
- html - 如何将这些 CSS 网格单元扩展到它们的内容?
- python - 对我来说最重要的问题:有没有更好的方法,如果有,你们能指出我正确的方向吗?
- python - 如何在 paramiko 连接中临时添加 host_key