Pandas 比较变量时按类别缩放未返回预期结果
Pandas Scaling as category not returning expected result when comparing variables
我正在学习一些 coursera 课程,其中一门我必须使用 pandas 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'
哪个returns:
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
我的代码
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
s>'Low'
其中returns:
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
正如你在他对 'High'>'Low'
和 returns '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
我正在学习一些 coursera 课程,其中一门我必须使用 pandas 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'
哪个returns:
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
我的代码
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
s>'Low'
其中returns:
0 False
1 False
2 False
3 True
4 False
5 False
6 False
dtype: bool
正如你在他对 'High'>'Low'
和 returns '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