简体   繁体   English

ValueError:int() 的无效文字,基数为 10:Python/IndexError 中的“”:列表索引超出范围

[英]ValueError: invalid literal for int() with base 10: '' in Python/ IndexError: list index out of range

在此处输入图像描述

I'm trying to learn Python and I'm working on a project.我正在尝试学习 Python 并且我正在做一个项目。 I want to split a column.我想拆分一列。 Column like this;像这样的列; income 60-80 120- 0-40 Here is my code: For def["min_income] line, I get invalid literal for int() with base error , for the other line (max_income) I receive list index out of range error.收入 60-80 120- 0-40 这是我的代码:对于 def["min_income] 行,我得到int() 的无效文字和基本错误,对于另一行 (max_income) 我收到列表索引超出范围错误。

income = df["Income"]
income = income.replace({"Unknown": ""})

df["min_income"] = income.apply(lambda x: int(x.split("-")[0]))
df["max_income"] = income.apply(lambda x: x.split("-")[1])

But the outcome give an error like this:但结果给出了这样的错误:

 df["min_income"] = income.apply(lambda x: int(x.split("-")[0]))
Traceback (most recent call last):

  File "<ipython-input-69-9be6a45724ad>", line 1, in <module>
    df["min_income"] = income.apply(lambda x: int(x.split("-")[0]))

  File "C:\Users\memin\anaconda3\lib\site-packages\pandas\core\series.py", line 4138, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)

  File "pandas\_libs\lib.pyx", line 2467, in pandas._libs.lib.map_infer

  File "<ipython-input-69-9be6a45724ad>", line 1, in <lambda>
    df["min_income"] = income.apply(lambda x: int(x.split("-")[0]))

ValueError: invalid literal for int() with base 10: ''

I want to split the income column into two different parts(columns)-min_income and max_income- as integer form.我想将收入列分成两个不同的部分(列)-min_income 和 max_income- 作为 integer 形式。 I check the error in the internet but I could not fix the problem.我检查了互联网上的错误,但我无法解决问题。 How can I solve this problem?我怎么解决这个问题? Also I tired.astype(int) func.我也累了.astype(int) func。

If you have this dataframe:如果你有这个 dataframe:

   income
0   60-80
1    0-40
2    120-
3  80-120
4    -255

Then:然后:

df[["min_income", "max_income"]] = df["income"].str.split("-", expand=True)
print(df)

Will create two columns "min_income" and "max_income" :将创建两列"min_income""max_income"

   income min_income max_income
0   60-80         60         80
1    0-40          0         40
2    120-        120           
3  80-120         80        120
4    -255                   255

You then can fill the blank values as you wish (and then convert to numeric format).然后,您可以根据需要填充空白值(然后转换为数字格式)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM