[英]Applying a map elementwise to every element on a Series (Pandas)
当我尝试以下操作时:
# 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)
我得到:
ValueError: Unkonwn format code 'g'for object of type 'str'
但是,以下方法效果很好
test = my_float_to_string(5.0)
print test
'5'
为什么我无法在Series
对象上逐个应用函数?
此外,为什么DataFrames和Series对于元素操作具有不同的方法名称(即,Series的map
与applymap
的applymap)
使用时
my_df['foo'] = my_df['foo'].map(float_to_string)
float_to_string
接收字符串,而不是浮点数。 要检查您是否可以添加
assert(isinstance(f, float))
在float_to_string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.