减少python for循环的时间复杂度

时间:2017-07-20 15:32:15

标签: python loops time-complexity ipython-notebook

我有python数据框,包含以下列:

Index([u'Academic Period', u'Academic Period Desc', u'Student ID',
       u'Subject', u'Course Number', u'Course Reference Number',
       u'Course Identification', u'Schedule Type', u'Instructor's ID',
       u'Highest Degree', u'Highest Degree Code',
       u'Instructor Position Employee Group'],
      dtype='object')

我现在尝试按行循环,检查并比较两个列值:

for i in df['Student ID']:
    if df['Course Reference Number'] >= 50000:
        if df['Highest Degree Code'] <= 7:
            print df["Instructor's ID"]
    else:
        if df['Highest Degree Code'] <= 6:
            print df["Instructor's ID"]

我的文件中有910,000多行,并且需要很长时间才能完成。

我可以将时间复杂度从O(n)降低到更低(使用任何可能的算法)吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

假设你有这个数据框:

import pandas as pd
df = pd.DataFrame({'Course Reference Number':[10000, 10000, 20000, 30000,
                   50000, 70000, 80000, 80000, 90000],
                   "Highest Degree Code":[7,6,1,8,7,6,8,6,9],
                   "Instructor's ID":range(9)})

df是:

   Course Reference Number  Highest Degree Code  Instructor's ID
0                    10000                    7                0
1                    10000                    6                1
2                    20000                    1                2
3                    30000                    8                3
4                    50000                    7                4
5                    70000                    6                5
6                    80000                    8                6
7                    80000                    6                7
8                    90000                    9                8

您可以使用布尔运算:

m_1 = df['Course Reference Number'] >= 50000
m_2 = df['Highest Degree Code'] <= 7
m_3 = df['Highest Degree Code'] <= 6
print df["Instructor's ID"][(m_1 & m_2) | ((~m_1) & m_3)].values

你会得到:

[1 2 4 5 7]

如果您想要结果行:

print df[(m_1 & m_2) | ((~m_1) & m_3)]

你会看到:

   Course Reference Number  Highest Degree Code  Instructor's ID
1                    10000                    6                1
2                    20000                    1                2
4                    50000                    7                4
5                    70000                    6                5
7                    80000                    6                7

答案 1 :(得分:1)

我不知道python,但是你可以通过提高效率将条件重新排序为潜在

for i in df['Student ID']:
    if df['Highest Degree Code'] <= 7:
        if df['Course Reference Number'] >= 500000:
            print df["Instructor's ID"]
        elif df['Highest Degree Code'] <= 6:
            print df["Instructor's ID"]

我重新订购了它,因为如果Highest Degree Code是&gt;您不想打印7,无论Course Reference Number.对我而言,检查是否首先要打印然后再打印到更多条件的内容似乎更合乎逻辑。

但是,如果更多次出现在哪里,此方法效率会更高:

Highest Degree Code is > 7

比有:

Highest Degree Code <=7 AND Course Reference Number < 50000