我试图简化熊猫和python的语法,当执行一个基本的熊猫操作。熊猫比较
我有4列:
- A_ID
- a_score
- B_ID
- b_score
我创建了一个新的标签称为基于以下DOC_TYPE:
- 一个> = B,DOC_TYPE:一个
- B> A,DOC_TYPE:乙
林在如何在大熊猫其中存在,但b计算挣扎不,在这个那么情况就需要成为标签。现在它返回else语句或b。 我需要创建2个额外的比较,其规模可能是有效的,因为我已经比较过之前的数据。寻找如何改进它。
df = pd.DataFrame({
'a_id': ['A', 'B', 'C', 'D', '', 'F', 'G'],
'a_score': [1, 2, 3, 4, '', 6, 7],
'b_id': ['a', 'b', 'c', 'd', 'e', 'f', ''],
'b_score': [0.1, 0.2, 3.1, 4.1, 5, 5.99, None],
})
print df
# Replace empty string with NaN
m_score = r['a_score'] >= r['b_score']
m_doc = (r['a_id'].isnull() & r['b_id'].isnull())
df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)
# Calculate higher score
df['doc_id'] = df.apply(lambda df: df['a_id'] if df['a_score'] >= df['b_score'] else df['b_id'], axis=1)
# Select type based on higher score
r['doc_type'] = numpy.where(m_score, 'a',
numpy.where(m_doc, numpy.nan, 'b'))
# Additional lines looking for improvement:
df['doc_type'].loc[(df['a_id'].isnull() & df['b_id'].notnull())] = 'b'
df['doc_type'].loc[(df['a_id'].notnull() & df['b_id'].isnull())] = 'a'
print df
你需要在现实中DOC_ID?或者它只是你的处理代码的一部分? – Psidom
只是处理代码的一部分,我们现在可以忽略它。 – spicyramen