繁体   English   中英

将地图元素逐级应用于系列(熊猫)上的每个元素

[英]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的mapapplymap的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.

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