情况说明
我正在使用某个分类器根据特定列中的值对DataFrame中的行进行分类。我的目标是根据某些条件将结果附加到一个新列或另一个新列中。当前的代码大致如下:
df = pd.DataFrame({'A': [list with classifier ids], # Only 3 ids, One word strings
'B': [List of text to be classified], # Millions of unique rows, lines of text around 5-25 words long
'C': [List of the old classes]} # Hundreds of possible classes, four digit integers stored as strings
df.sort_values('A', inplace=True)
new_col1, new_col2 = [], []
for name, group in df.groupby('A', sort=False):
classifier = classy_dict[name]
vectors = vectorize(group.B.values)
preds = classifier.predict(vectors)
scores = classifier.decision_function(vectors)
for tup in zip(preds, scores, group.C.values):
if tup[2] == tup[0]:
new_col1.append(np.nan)
new_col2.append(tup[2])
else:
new_col1.append(str(classifier.classes_[tup[1].argsort()[-5:]]))
new_col2.append(np.nan)
df['D'] = new_col1
df['E'] = new_col2
问题
我担心groupby
不会按照我期望的从上到下、按出现顺序迭代。当sort=False
时,迭代顺序没有在文档中进行解释。
我的期望
我想确认一下groupby('col', sort=False)
是否按照我期望的从上到下、按出现顺序迭代。如果有更好的方法来使所有内容正常工作,欢迎提出建议。
这是我用来测试关于sort=False
迭代顺序理论的代码:
from numpy.random import randint
import pandas as pd
from string import ascii_lowercase as lowers
df = pd.DataFrame({'A': [lowers[randint(3)] for _ in range(100)],
'B': randint(10, size=100)})
print(df.A.unique()) # unique values in order of appearance per the docs
for name, group in df.groupby('A', sort=False):
print(name)
编辑:上述代码使其看起来以我所期望的方式运作,但如果有确凿的证据,我希望能得到更多证明。
请注意,这里的“appear”是指表面上看起来如此,但并不确定是否确实如此。
groupby
函数的操作,实际数据与其无关。我已经简化了问题描述,并添加了数据样本说明。 - Eric Ed Lohmar