简体   繁体   中英

Applying a map elementwise to every element on a Series (Pandas)

When I try the following:

# Define the mapping
def my_float_to_string(f):
  return "{:g}".format(f)

# This returns numpy.float64
type(my_xls['Subject'][0])

my_df['foo'] = my_df['foo'].map(float_to_string)

I get:

ValueError: Unkonwn format code 'g'for object of type 'str'

However, the following works well

test = my_float_to_string(5.0)
print test 
'5'

Why am I unable to apply my function elementwise on my Series object?

Also, why do DataFrames and Series have different method names for elementwise operations (ie map for Series vs applymap for DataFrames)

When using

my_df['foo'] = my_df['foo'].map(float_to_string)

float_to_string receive a string and not a float. To check that you can add an

assert(isinstance(f, float))

in float_to_string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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