try this :-

carprice['fueltype']=carprice['fueltype'].map({'gas':1,'diesel':0})

or you can do

carprice['fueltype']=carprice['fueltype'].apply(lambda x: 1 if x =='gas' else 0))

Map basically operates on the series while apply works on each cell.

Answer from Yash Thenuan on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 55183519 › attributeerror-str-object-has-no-attribute-map
python - AttributeError: 'str' object has no attribute 'map' - Stack Overflow
March 15, 2019 - Is r a string or a dict? If it's a string, then s=r["Customer"] should crash with TypeError: string indices must be integers. If it's a dict and if the value associated with "Customer" is a list, then s.map should crash with AttributeError: 'list' object has no attribute 'map'.
Discussions

python - AttributeError: 'str' object has no attribute - Stack Overflow
I'm pretty new to python programming and I wanted to try my hand at a simple text adventure game, but I've immediately stumbled on a roadblock. class userInterface: def __init__(self, roomID, More on stackoverflow.com
🌐 stackoverflow.com
python - AttributeError: 'str' object has no attribute 'str' - Stack Overflow
My pandas DataFrame looks like following. I am trying to remove '$' and ',' from my income column and then apply on my original dataframe. so I created below function. However, it is giving me error More on stackoverflow.com
🌐 stackoverflow.com
Sequence of Map - `AttributeError: 'str' object has no attribute 'items'`` when data contains Map in Map
Following schema describes a sequence map: schema.yml type: map required: yes mapping: "employees": type: seq required: yes sequence: - type: map required: yes mapping: "name": ... More on github.com
🌐 github.com
4
May 4, 2015
python - AttributeError: 'str' object has no attribute 'description' - Stack Overflow
Im new in Python3. I wrote a little text-adventure but i don't know how to use the input string to access the object properties. class Object: def __init__(self, name, description): sel... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Esri Community
community.esri.com › t5 › arcgis-api-for-python-questions › str-object-has-no-attribute › td-p › 1053478
Solved: 'str' object has no attribute - Esri Community
September 14, 2021 - Solved: Searching through the other messages hasn't helped me with this. I like to figure things out on my own, but I'm stumped. I copied the deep_copy_content part
🌐
GitHub
github.com › Grokzen › pykwalify › issues › 16
Sequence of Map - `AttributeError: 'str' object has no attribute 'items'`` when data contains Map in Map · Issue #16 · Grokzen/pykwalify
May 4, 2015 - Sequence of Map - AttributeError: 'str' object has no attribute 'items'` when data contains Map in Map#16
Author   quamilek
🌐
Stack Overflow
stackoverflow.com › questions › 65822233 › attributeerror-str-object-has-no-attribute-description
python - AttributeError: 'str' object has no attribute 'description' - Stack Overflow
The attribute error occurs because strings do not have an attribute named description. ... Use a dictionary to map the user input string to an object.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › 'str' object has no attribute error?
r/learnpython on Reddit: 'Str' object has no attribute error?
November 9, 2023 -

I have some experience with programming in Java, C++, etc. and I am trying to write a simple "To-Do List" program to get used to Python. I'm running into the error: str object has no attribute "completed" when trying to iterate over the list of tasks, check their completion status, and display them.

Here are some relevant pieces of the program:

Constructor for the Task class

def __init__(self, task_name):

self.task_name = task_name

self.completed = False

In the ToDoList class (which holds a list of the task instances created by the user) this is the iteration throwing the error in question:

for idx, task in enumerate(self.tasks, start=1):

status = "Completed" if task.completed else "Incomplete"

print(f"{idx}. {task.task_name} - {status}")

I thought, potentially the problem lies in the fact that the enumerate function is grabbing the string value of the task instance, rather than the object itself, so maybe I can iterate over it the old fashioned way and get around it. So I tried it like this:

counter = 1

for task in self.tasks:

status = "Completed" if task.completed else "Incomplete"

print(f"{counter}. {task.task_name} - {status}")

counter += 1

Yet, it throws the same error. I know there is something I am missing or not understanding correctly here. What is it?

Thanks!

Top answer
1 of 4
5

Look at these two lines:

vertex = my_queue.pop()
# ...
my_queue = str(test)

So, after the first time through the loop, my_queue is obviously a str, because you explicitly convert it to one.

You can see a list of String Methods and Common Sequence Operations. Notice that pop doesn't appear anywhere there. That's because pop is only a method of Mutable Sequence Types like list. Which is exactly what this error is telling you:

AttributeError: 'str' object has no attribute 'pop'

And even if there were such a method, what would you expect it to return? The first character of the string? How would that work with for n_vertex in vertex['neighbors'], which clearly expects vertex to be a dict (or other Mapping type), not a single-character string?


I'm not sure what exactly you're trying to do at the end, but I suspect that removing the str() call won't be enough on its own to solve all of your problems. You're appending to a list named test that isn't defined anywhere in the function, so presumably it's a global variable. You then throw away whatever was in my_queue and instead assign it to that global variable. That can't possibly be what you want. My guess—but this is only a guess—is that you want to replace those last two lines with this:

my_queue.insert(0, my_data[int_vertex])
2 of 4
0

pop method is not supported by string objects in python. I believe my_queue is not referring to list object but it referring to string. via debug or using type(), isinstance() builtin you can come to know which data type my_queue is referring to.

Top answer
1 of 2
4

There are a few problems with your script. Firstly, to define a layer to load on completion, you must an additional parameter of type QgsProcessingParameterFeatureSink in the initAlgorithm() method.

Then, when you call the native fix geometries algorithm inside the processAlgorithm() method, the output parameter should be: parameters['OUTPUT'].

That will give you the checkbox in the dialog: 'Open output file after running algorithm'

Renaming the output file is a little more involved. To do this you need to add a Layer Post Processor class and rename the layer inside this class. Then create an instance of this class at the end of the processAlgorithm() method and pass it to the setPostProcessor() method chained to the layerToLoadOnCompletionDetails() method of the QgsProcessingContext object.

Working modified script below (maybe not perfect but it's working!):

# -*- coding: utf-8 -*-

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsVectorLayer,
                       QgsProcessingLayerPostProcessorInterface)
from qgis import processing


class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    INPUT1 = 'INPUT1'
    OUTPUT = 'OUTPUT'
    def tr(self, string):
        return QCoreApplication.translate('Processing', string)
    def createInstance(self):
        return ExampleProcessingAlgorithm()
    def name(self):
        return 'testpersistence'
    def displayName(self):
        return self.tr('Testpersistence')
    def group(self):
        return self.tr('Example scripts')
    def groupId(self):
        return 'examplescripts'
    def shortHelpString(self):
        return self.tr("Testing the script")

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT1,
                self.tr('Input layer 1'),
                [QgsProcessing.TypeVectorAnyGeometry]
            )
        )
        self.addParameter(QgsProcessingParameterFeatureSink(
            self.OUTPUT,
            self.tr("Output layer"),
            QgsProcessing.TypeVectorAnyGeometry))
        
    def processAlgorithm(self, parameters, context, feedback):
        source1 = self.parameterAsSource(parameters,self.INPUT1,context)
        fixgeometries1_result = processing.run(
            'native:fixgeometries',
            {
                'INPUT': parameters['INPUT1'],
                'OUTPUT': parameters['OUTPUT']
            },
            is_child_algorithm=True,
            context=context,
            feedback=feedback)

        dest_id = fixgeometries1_result['OUTPUT']
        
        if context.willLoadLayerOnCompletion(dest_id):
            context.layerToLoadOnCompletionDetails(dest_id).setPostProcessor(MyLayerPostProcessor.create())

        return {}
        
        
class MyLayerPostProcessor(QgsProcessingLayerPostProcessorInterface):
    # Courtesy of Nyall Dawson: https://gist.github.com/nyalldawson/26c091dd48b4f8bf56f172efe22cf75f
    instance = None

    def postProcessLayer(self, layer, context, feedback):  # pylint: disable=unused-argument
        if not isinstance(layer, QgsVectorLayer):
            return

        layer.setName('Renamed layer')
        

    # Hack to work around sip bug!
    @staticmethod
    def create() -> 'MyLayerPostProcessor':
        """
        Returns a new instance of the post processor, keeping a reference to the sip
        wrapper so that sip doesn't get confused with the Python subclass and call
        the base wrapper implementation instead... ahhh sip, you wonderful piece of sip
        """
        MyLayerPostProcessor.instance = MyLayerPostProcessor()
        return MyLayerPostProcessor.instance

The code for the MyLayerPostProcessor() class I adapted from a github gist of Nyall Dawson's here.

See a gif below showing this script working and loading a renamed layer:

2 of 2
4

You were almost there.
Your problem was you were reloading the layer instead of taking its data and reloading it as a new named layer.

This should work for you:

fixgeometries1_result = processing.run(
        'native:fixgeometries',
        {
            # passing the input
            'INPUT': parameters['INPUT1'],
            'OUTPUT': 'memory:'
        },
        is_child_algorithm=True,
        context=context,
        feedback=feedback)

uri = fixgeometries1_result['OUTPUT'].dataProvider().dataSourceUri()

layer1 = QgsVectorLayer(uri,"layername","memory")

QgsProject.instance().addMapLayer(layer1)
🌐
Reddit
reddit.com › r/learnpython › how do i fix this : attributeerror: 'str' object has no attribute 'current'
r/learnpython on Reddit: How do i fix this : AttributeError: 'str' object has no attribute 'current'
December 7, 2023 -

There is something wrong with this function. It shows no errors, but when I try to run it, It says AttributeError: 'str' object has no attribute 'current'. (BTW, i am trying to run it as a flet on spyder)

def leapyears(e):

days_in_month = {1: 31, 3: 31, 4: 30, 5:31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31 }

month = int(EnterMonth_text.value)

year = int(EnterYear_text.value)

if year % 100 == 0:

if year % 400 == 0:

leap_year = True

elif year % 4 == 0:

leap_year = True

else:

leap_year = False

if month == 2 :

if leap_year:

days_in_month[2] = 29

else:

days_in_month[2]= 28

output_textfield.value= days_in_month[month]

page.update()

🌐
Stack Exchange
gamedev.stackexchange.com › questions › 206528 › python-ursina-mesh-importer-py-attributeerror-str-object-has-no-attribute-g
Python ursina\mesh_importer.py: AttributeError: 'str' object has no attribute 'glob' - Game Development Stack Exchange
July 19, 2023 - Loading assets: Assets/Models/Plane.obj Traceback (most recent call last): File "C:\Users\x\Desktop\WeatherSim\WeatherSim.py", line 207, in <module> Assets.LoadM("Empty","Assets/Models/Plane.obj") File "C:\Users\x\Desktop\WeatherSim\WeatherSim.py", line 163, in LoadM setattr(self,n,load_model(obj_to_ursinamesh(obj))) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\x\AppData\Local\Programs\Python\Python311\Lib\site-packages\ursina\mesh_importer.py", line 224, in obj_to_ursinamesh for f in path.glob(f'**/{name}.obj'): ^^^^^^^^^ AttributeError: 'str' object has no attribute 'glob' C:\Users\x\Desktop\WeatherSim>
🌐
GitHub
github.com › langflow-ai › langflow › issues › 1837
AttributeError: 'str' object has no attribute 'items' · Issue #1837 · langflow-ai/langflow
May 5, 2024 - Describe the bug AttributeError: 'str' object has no attribute 'items' Langflow Version 0.6.17 Browser and Version Browser Edge Version 124.0.2478.80 (Official build) (x86_64) Additional context [05/05/24 02:04:32] ERROR 2024-05-05 02:04...
Author   artemus717
🌐
Quora
quora.com › What-can-I-do-if-I-have-attribute-error-str-object-has-no-attribute-re
What can I do if I have attribute error: 'str' object has no attribute 're'? - Quora
Answer: Work out what object should have that re attribute and why your code is using a string not the correct object. In my experience these type of errors tend to happen because of misleading variable names: if your variables are all using ...
🌐
freeCodeCamp
forum.freecodecamp.org › python
AttributeError: 'str' object has no attribute 'get' - Python - The freeCodeCamp Forum
December 2, 2021 - The formatting of your post is hella weird - how about you just include a link to your replit · For the catplot, you need to add a line fig=fig.fig before saving - as the test is not designed for standard object sns is returning · Am sorry for my formatting errors Jagaya, am new to this .