简体   繁体   English

如何解析字符串索引在数据分析中必须是整数?

[英]How to resolve string indices must be integers in data analysis?

I have downloaded some data, so I wanted to change some values into boolean type:我已经下载了一些数据,所以我想将一些值更改为 boolean 类型:

for dataset in loan_df:
    dataset['Gender'] = dataset['Gender'].replace({'male' : 1 , 'female' : 0} , inplace = True)

but it is giving me this error:但它给了我这个错误:

TypeError: string indices must be integers

I also tried this code:我也试过这段代码:

for dataset in loan_df:
    dataset['Gender'] = dataset['Gender'].map({'male' : 1 , 'female' : 0}).astype(int)

But it is still giving the same error.但它仍然给出同样的错误。 Do you know how to resolve this error?你知道如何解决这个错误吗?

I believe the loan_df is a pandas DataFrame, therefore when you are iterating trough it with the for loop, the iterator is a Series .我相信loan_df是 pandas DataFrame,因此当您使用for循环遍历它时,迭代器是Series That is why, when you try ['Gender'] you are actually indexing it and an integer is expected.这就是为什么当您尝试['Gender']时,您实际上是在为其编制索引,并且预计会出现 integer。

The solution would be to remove the loop:解决方案是删除循环:

loan_df['Gender'] = loan_df['Gender'].replace({'male' : 1 , 'female' : 0})

Assuming loan_df is a singular DataFrame, I create an emulated DataFrame like so:假设loan_df是一个奇异的DataFrame,我创建一个模拟的DataFrame,如下所示:

loan_df = pd.DataFrame({"Gender":["male","female"]})

I reproduced the error with the following code, but I also included print statements:我使用以下代码重现了该错误,但我还包含了打印语句:

for dataset in loan_df:
    print(dataset)
    print(type(dataset))
    dataset['Gender'] = dataset['Gender'].replace({'male' : 1 , 'female' : 0} , inplace = True)

Output: Output:

Gender
<class 'str'>
...

TypeError: string indices must be integers

When you iterate through the DataFrame, dataset will be the column names.当您遍历 DataFrame 时, dataset将是列名。

Try using the below command:尝试使用以下命令:

loan_df['Gender'].replace({'male' : 1 , 'female' : 0} , inplace = True)

By indicating the inplace parameter, you do not have to reassign it back to loan_df .通过指示 inplace 参数,您不必将其重新分配回loan_df

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

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