Python 将地图元素化应用于系列上的每个元素(熊猫)
当我尝试以下方法时:Python 将地图元素化应用于系列上的每个元素(熊猫),python,pandas,Python,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 typ
# 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'
为什么我无法在我的系列
对象上以元素方式应用我的函数
此外,为什么数据帧和序列在使用时具有不同的元素操作方法名称(即序列的map
与数据帧的applymap
)
my_df['foo'] = my_df['foo'].map(float_to_string)
float\u to\u string
接收字符串而不是float。检查是否可以添加
assert(isinstance(f, float))
当使用
my_df['foo'] = my_df['foo'].map(float_to_string)
float\u to\u string
接收字符串而不是float。检查是否可以添加
assert(isinstance(f, float))
在
浮动到字符串中
因为它们是字符串而不是浮动。。。要将数字格式化为浮点数,它必须是浮点数(或至少是数字),谢谢Jon@,但我很困惑,my_df['foo']
保存浮点数(请参阅我更新的OP)。更改函数以包含第一行print f,键入(f)
。。。看看你得到了什么…因为它们是字符串而不是浮点数。。。要将数字格式化为浮点数,它必须是浮点数(或至少是数字),谢谢Jon@,但我很困惑,my_df['foo']
保存浮点数(请参阅我更新的OP)。更改函数以包含第一行print f,键入(f)
。。。看看你得到了什么…谢谢,你是对的,事实证明我在我的数据帧中有几个nan值(其他所有的都是float64,所以我看不到)。在float
s的数据帧列中包含nan应该不是问题。例如,“{:g}”.format(np.NaN)
可以很好地工作并打印“NaN”。查看na_action
参数到Series.map
谢谢,你是对的,结果是我的数据帧中有几个NaN值(其他所有内容都是float64,所以我看不到它)在float
s的DataFrame列中包含NaN应该不是问题。例如,“{:g}”.format(np.NaN)
可以很好地工作并打印“NaN”。请查看na_action
参数到Series.map