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 Overflowtry 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.
Map function with in "apply" works fine if your column is of dataframe type rather than a series. To convert a column from series to dataframe enclose it with in '[]'
carprice[['fueltype']]=carprice[['fueltype']].apply(lambda x: x.map({'gas':1,'diesel':0}))
python - AttributeError: 'str' object has no attribute - Stack Overflow
python - AttributeError: 'str' object has no attribute 'str' - Stack Overflow
Sequence of Map - `AttributeError: 'str' object has no attribute 'items'`` when data contains Map in Map
python - AttributeError: 'str' object has no attribute 'description' - Stack Overflow
I'm not sure why you're using map here. Iterating over a dictionary gives you the keys only, which are strings. Just use the dict directly; you don't need lambda either:
my_dict.get('a').get('b')
(As noted in the comments, you shouldn't use dict as the name of your variable.)
When you access a dictionary d as an iterator, you iterate over the keys. You are essentially doing
dict(map(lambda x:x.get('a').get('b'), ['a']))
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!
The error means exactly what it says:
AttributeError: 'str' object has no attribute 'DataFrame'
^ ^ ^
the kind of error | |
the thing you tried to use what was missing from it
The line it's complaining about:
df = pd.DataFrame(date, columns = ['Date'])
^ ^
| the attribute the error said was missing
the thing the error said was a string
has been working no problem until I added a few lines of code above
Evidently, somewhere in the "few lines of code above", you caused pd to be a string. And sure enough, when we look at those few lines of code, we find:
pd = PDays[j]
^ ^
| the string that you're making it into
the thing that you're making a string
You are reassign pd
import pandas as pd
to
pd = PDays[j]
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])
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.
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:

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)
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()