0
def mapTarget(target):
    if target == 0:
        return 'setosa'
    if target == 1:
        return 'versicolor'
    if target == 2 :
        return 'virgincia'



ir = load_iris()
df = pd.DataFrame(ir['data'], columns = ir['feature_names'])
df['target'] = ir['target']
df['target_name'] = map(mapTarget,df['target'])
print(df)

Python 3.x In the above program i'm trying to map the target value with the target name in the iris dataset. But it always return something like map object at 0x000000001466DD68

4
  • In Python-3.x, a map is not calculated directly, it is done lazily. You better use df['target_name'] = df['target'].apply(mapTarget) for instance. Commented Jan 3, 2018 at 15:26
  • Have you tried df['target_name'] = list(map(mapTarget,df['target'])) Commented Jan 3, 2018 at 15:27
  • You also need to put your python version in Commented Jan 3, 2018 at 15:28
  • And also print what your df is after this line df = pd.DataFrame(ir['data'], columns = ir['feature_names']). Commented Jan 3, 2018 at 15:28

3 Answers 3

1

In Python map is a generator. To turn it into a list, simply change

df['target_name'] = map(mapTarget,df['target'])

to

df['target_name'] = list(map(mapTarget,df['target']))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Daniel. I got that. That's a simple data structure.
If this answered your question please accept as the answer. Otherwise, are there any other errors which you have?
map is not a generator, but it is an iterator.
1

In Python 3, the map function returns an iterable. This means that it is more lightweight and still allows you to iterate through the objects.

if you want to convert it to a list, you can call the list function. This is very easy. You can just change this line

df['target_name'] = map(mapTarget,df['target'])

to

df['target_name'] = list(map(mapTarget,df['target']))

However, if you only wish to iterate through the map and not print it out, you might as well keep it as a map object because it will be faster and cleaner.

Comments

0
import pandas as pd
from sklearn.datasets import load_iris

def mapTarget(target):
    if target == 0:
        return 'setosa'
    elif target == 1:
        return 'versicolor'
    elif target == 2:
        return 'virginica'
    else:
        return 'unknown'  # just in case there's an unexpected value

# Load the iris dataset
ir = load_iris()

# Create a DataFrame with the iris data
df = pd.DataFrame(ir['data'], columns=ir['feature_names'])

# Add the target column
df['target'] = ir['target']

# Map the target values to target names
df['target_name'] = df['target'].map(mapTarget)

# Print the DataFrame
print(df)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.