简体   繁体   English

如何拆分字符串并删除 dataframe 中每一行的第一项? 关键错误 18

[英]How can I split my string and delete the first item for every row in my dataframe? key error 18

enter image description here在此处输入图像描述

I keep getting key error 18 and dont know how to solve it.我不断收到关键错误 18 并且不知道如何解决它。 I am trying to split the values of a column and delete the first element of the list.我正在尝试拆分列的值并删除列表的第一个元素。

This is my code:这是我的代码:

 last_name= []

for i in train.index:

#Split at space and delete the first name  

   name_id = test_df_bin['Name'][i].split(' ')
   del name_id[0]

 #list of last name
   last_name.append(name_id[0])


test_df_bin['Surname'] = last_name`

*Error messege: *错误信息:

KeyError Traceback (most recent call last) File ~\Anaconda\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance) 3620 try: -> 3621 return self._engine.get_loc(casted_key) 3622 except KeyError as err: KeyError Traceback (最近一次调用最后) File ~\Anaconda\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance) 3620 try: -> 3621返回 self._engine.get_loc(casted_key) 3622 除了 KeyError 作为错误:

KeyError: 18*密钥错误:18 *

I strongly suggest against looping unless strictly necessary.除非绝对必要,否则我强烈建议不要循环。 In this case you can achieve your desired solution with:在这种情况下,您可以通过以下方式实现所需的解决方案:

test_df_bin['Surname'] = test_df_bin['Name'].str.split().str[1:]

If you'd like the output of the split() joined back into a single string, then:如果您希望将split()的 output 重新连接成一个字符串,那么:

test_df_bin['Surname'] = [' '.join(x) for x in test_df_bin['Name'].str.split().str[1:]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何选择和删除数据库的第一行? - How can I select and delete the first row of my database? 在我的多索引 pandas dataframe 中,我怎么能 select 只为每个级别(0)的前两行? - how can i select only the first two rows for every level (0) in my multiindex pandas dataframe? 如何按年或月拆分我的 dataframe - How can I split my dataframe by year or month 如何将电子表格中的第一行用作数据框列名,而不是0 1 2…等? - How do I use my first row in my spreadsheet for my Dataframe column names instead of 0 1 2…etc? Python 如何为列表中的每个项目创建集合? - Python How can I create sets for every item in my list? 如何将我的 function 应用到 dataframe 的第一行? - How to apply my function to the first row of a dataframe? 使用 Pandas Dataframe,如何拆分特定列中的字符串,然后用拆分的第一个索引替换该字符串? - Using a Pandas Dataframe, how can I split the strings in a specific column and then replace that string with the first index of the split? 我怎样才能使用 string.split() 所以我用特定长度分割我的字符串[保留] - How can I use string.split() so I split my string with a specific length [on hold] 如何获取列表中每个项目的第一个和最后一个项目 - How can I get the first and last item of every item of list 如何删除字符串中引号内的内容? - How can I delete the content inside a quotation mark in my string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM