[英]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.