Pandas 在数据系列上应用lower()方法时,应用映射函数引发错误
有关以下代码:Pandas 在数据系列上应用lower()方法时,应用映射函数引发错误,pandas,lambda,apply,Pandas,Lambda,Apply,有关以下代码: # 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]
# 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”对象不hap方法“map”
我做错了什么?当你
在数据帧上应用时,比如df[['Response']]。应用(…)
,lambda立即接收整个df.Response
列,这样你就可以使用一系列方法,比如str
和map
如果您改为apply
对类似df['Response'].apply(…)
的序列,lambda将接收df.Response
的单个字符串,而不是整个df.Response
列,因此需要相应地更改映射:
mapping={'yes':1.0,'no':0.0,'maybe':0.5}
df['Response']=df['Response'].apply(lambda x:mapping[x.lower())
#名称响应
#0芦苇0.0
#1.0.5
#2 Kaustubh 1.0
#3 Vikas 1.0
#4马希马0.5
#5阿克什1.0
当您对数据帧(如df[['Response']])应用时,lambda会立即接收整个df.Response
列,因此您可以使用一系列方法,如str
和map
如果您改为apply
对类似df['Response'].apply(…)
的序列,lambda将接收df.Response
的单个字符串,而不是整个df.Response
列,因此需要相应地更改映射:
mapping={'yes':1.0,'no':0.0,'maybe':0.5}
df['Response']=df['Response'].apply(lambda x:mapping[x.lower())
#名称响应
#0芦苇0.0
#1.0.5
#2 Kaustubh 1.0
#3 Vikas 1.0
#4马希马0.5
#5阿克什1.0
太棒了!谢谢你解释这个问题……)令人惊叹的!谢谢你解释这个问题……)