Python 比较变量时,按类别缩放不会返回预期结果
我正在学习一些coursera课程,其中一门课程我必须使用pandasPython 比较变量时,按类别缩放不会返回预期结果,python,pandas,scale,categories,boolean-logic,Python,Pandas,Scale,Categories,Boolean Logic,我正在学习一些coursera课程,其中一门课程我必须使用pandasastype函数对数据框中的一些值进行分类。作为练习的一部分,我必须比较成绩,看看astype函数是否确实将它们按顺序排列,给定的练习有效,但我后来开发的练习无效。以下是代码: 工作代码 import pandas as pd import numpy as np df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
astype
函数对数据框中的一些值进行分类。作为练习的一部分,我必须比较成绩,看看astype
函数是否确实将它们按顺序排列,给定的练习有效,但我后来开发的练习无效。以下是代码:工作代码
import pandas as pd
import numpy as np
df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor'])
df.rename(columns={0: 'Grades'}, inplace=True)
grades = df['Grades'].astype('category',
categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],
ordered=True)
grades > 'C'
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
s>'Low'
返回:
excellent True
excellent True
excellent True
good True
good True
good True
ok True
ok False
ok False
poor False
poor False
Name: Grades, dtype: bool
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
我的代码
import pandas as pd
import numpy as np
df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor'])
df.rename(columns={0: 'Grades'}, inplace=True)
grades = df['Grades'].astype('category',
categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],
ordered=True)
grades > 'C'
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
s>'Low'
返回:
excellent True
excellent True
excellent True
good True
good True
good True
ok True
ok False
ok False
poor False
poor False
Name: Grades, dtype: bool
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
正如您所看到的,当他比较
'High'>'Low'
时,它返回'False'
。我做错什么了吗?我有没有失去任何概念?谢谢。您忘记分配输出:
print (s > 'Low')
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
s = s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
print (s > 'Low')
0 False
1 False
2 True
3 True
4 False
5 True
6 False
dtype: bool
您忘记分配输出:
print (s > 'Low')
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
s = s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
print (s > 'Low')
0 False
1 False
2 True
3 True
4 False
5 True
6 False
dtype: bool
明白了,函数astype只返回值,但不更改函数。非常感谢你。顺便说一句,coursera的结果和我的一样,这让我很困惑。明白了,函数astype只返回值,但不改变函数。非常感谢你。顺便说一句,coursera的成绩和我的一样,这让我感到困惑。