python 中 pandas DataFrame 上的 map() 函数无法按预期工作
map() function on pandas DataFrame in python does not work as expected
我尝试了下面的代码并研究了很长时间才更正它。但是我不知道我做错了什么。
def hiLow(x):
if x > 10:
print(x, 'is greater than 10')
df['High/Low'] = 'High'
else:
print(x, 'is less than 10' )
df['High/Low'] = 'Low'
df['total'].map(hiLow)
我预计它会在 'High/Low' 列的第二行和第三行添加 'High'。
当我用 df['High/Low'] = x
替换 df['High/Low'] = 'High'
和 df['High/Low'] = 'Low'
时,它会为所有行打印 15。
图中,
- 这个输出是正确的
- 为什么这都退回了'None'
- 为什么在第 4 点显示为 'int64'
时显示 'object'
def hiLow(x):
if x > 10:
print(x, 'is greater than 10')
str_answer = 'High'
else:
print(x, 'is less than 10' )
str_answer = 'Low'
return str_answer
df['High/Low'] = df['total'].apply(lambda x: hiLow(x) )
我尝试了下面的代码并研究了很长时间才更正它。但是我不知道我做错了什么。
def hiLow(x):
if x > 10:
print(x, 'is greater than 10')
df['High/Low'] = 'High'
else:
print(x, 'is less than 10' )
df['High/Low'] = 'Low'
df['total'].map(hiLow)
我预计它会在 'High/Low' 列的第二行和第三行添加 'High'。
当我用 df['High/Low'] = x
替换 df['High/Low'] = 'High'
和 df['High/Low'] = 'Low'
时,它会为所有行打印 15。
图中,
- 这个输出是正确的
- 为什么这都退回了'None'
- 为什么在第 4 点显示为 'int64' 时显示 'object'
def hiLow(x):
if x > 10:
print(x, 'is greater than 10')
str_answer = 'High'
else:
print(x, 'is less than 10' )
str_answer = 'Low'
return str_answer
df['High/Low'] = df['total'].apply(lambda x: hiLow(x) )