1
現在、私はカラム間の比較を行っているPandas Dataframeを持っています。比較が行われているときに空の列がある場合が見つかりました。何らかの理由で比較すると、以外の値が返されます。私は空にそれをきれいにするために余分な声明を追加しました。私がこれを簡略化し、単一のステートメントを持つことができるかどうかを調べる。あなたが列(複数可)とboolean indexing
による選択のためにも、代わりにapply
をnumpy.where
を使用することができますパンダの改善
df['doc_type'].loc[(df['a_id'].isnull() & df['b_id'].isnull())] = ''
コード
df = pd.DataFrame({
'a_id': ['A', 'B', 'C', 'D', '', 'F', ''],
'a_score': [1, 2, 3, 4, '', 6, ''],
'b_id': ['a', 'b', 'c', 'd', 'e', 'f', ''],
'b_score': [0.1, 0.2, 3.1, 4.1, 5, 5.99, ''],
})
print df
# Replace empty string with NaN
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
df['doc_type'] = df.apply(lambda df: 'a' if df['a_score'] >= df['b_score'] else 'b', axis=1)
print df
# Update type when is empty
df['doc_type'].loc[(df['a_id'].isnull() & df['b_id'].isnull())] = ''
print df