程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在数据系列上应用lower()方法时,pandas应用地图函数抛出错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在数据系列上应用lower()方法时,pandas应用地图函数抛出错误?

开发过程中遇到在数据系列上应用lower()方法时,pandas应用地图函数抛出错误的问题如何解决?下面主要结合日常开发的经验,给出你关于在数据系列上应用lower()方法时,pandas应用地图函数抛出错误的解决方法建议,希望对你解决在数据系列上应用lower()方法时,pandas应用地图函数抛出错误有所启发或帮助;

对于以下代码:

# Reading the input
import ast,sys
input_str = sys.stdin.read()
input_List = ast.literal_eval(input_str)
# Storing the names in a variable 'name'
name = input_List[0]
# Storing the responses in a variable 'repsonse'
response = input_List[1]

import pandas as pd 
df = pd.DataFrame({'name': name,'Response': responsE})

提供的输入如下:

['Reetesh','Shruti','Kaustubh','Vikas','Mahima','Akshay']
['No','Maybe','yes','Yes','maybe','Yes']

所需的输出如下:

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/d3FIi.png

当我尝试如下操作时:

def res_map(X):
    return x.map({'Yes': 1,'yes': 1,'No': 0,'no': 0,'Maybe': 0.5,'maybe': 0.5})

df[['Response']] = df[['Response']].apply(res_map)

# Print the final DataFrame
print(df)

效果很好..

但是当我尝试这样的事情时:

df['Response'] = df['Response'].apply(lambda x: x.str.lower().map({'yes':1.0,'no':0.0,'maybe':0.5}))

我收到一个错误“str”对象不符合方法“map”...

我在这里做错了什么?

解决方法

当您在 apply 这样的 DataFrame 上 df[['Response']].apply(...) 时,lambda 会立即接收整个 df.Response 列,因此您可以使用 str{{1} 等系列方法}.

如果您在像 @H_230_5@map 这样的系列上改为 apply,则 lambda 接收 df['Response'].apply(...) 的单个字符串而不是整个 df.Response 列,因此需要更改映射相应地:

df.Response

大佬总结

以上是大佬教程为你收集整理的在数据系列上应用lower()方法时,pandas应用地图函数抛出错误全部内容,希望文章能够帮你解决在数据系列上应用lower()方法时,pandas应用地图函数抛出错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。