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}))
'Str' object has no attribute error?
python - AttributeError: 'str' object has no attribute 'map' - Stack Overflow
Dataset object has no attribute map
AttributeError: 'str' object has no attribute 'get'
Videos
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!
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']))
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()
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)