状況1,000を超えるテーブルを持つデータベースで作業しているときにこの問題が発生しています。列名の値に基づいてテーブル名をフィルタリングしたいと思います。str.contains()
データフレームでを実行しようとしていますが、エラーが発生します。エラー読み取り"None of [Float64Index([nan, nan, nan, nan, nan], dtype='float64')] are in the [columns]"
ダミーデータでエラーを再現することができました。
私の目標は、列名「date」が含まれているため、「table5」にフィルタリングされたデータフレームを返すことです。
listoftables = ['table1', 'table2', 'table3', 'table4', 'table5']
columnnames = [['age', 'name', 'school'],
['age', 'name', 'school'],
['age', 'name', 'school'],
['age', 'name', 'school'],
['audit', 'auditrunlist', 'date']]
example = pd.DataFrame(
{'TableName': listoftables,
'col_names' : columnnames
})
example[(example['col_names'].str.contains('date'))]
リスト内の文字列を検索しているため、エラーが発生したと思います。私をさらに混乱させるのは、実行example[(example['col_names'].str.contains('[audit, auditrunlist, date]'))]
すると同じエラーが発生することです。
リストではない列をもう1つ追加すると、期待どおりの結果が得られます。
listoftables = ['table1', 'table2', 'table3', 'table4', 'table5']
columnnames = [['age', 'name', 'school'],
['age', 'name', 'school'],
['age', 'name', 'school'],
['age', 'name', 'school'],
['audit', 'auditrunlist', 'date']]
no_list_columnnames = ['age, name, school',
'age name school',
'age name school',
'age name school',
'audit auditrunlist date']
example = pd.DataFrame(
{'TableName': listoftables,
'col_names' : columnnames,
'no_list_col_names' : no_list_columnnames
})
# this returns what i expect
example[(example['no_list_col_names'].str.contains('date'))]
2つの結果があると思います。パンダのデータフレーム内のリスト内を検索する方法を見つけるか、パンダのデータフレーム内の列をリストから文字列に変換する方法を見つけることができます。
リストを列としてパンダのデータフレームをフィルタリングするためのより良い方法は何ですか?
この問題を指摘してくれてありがとう、それは面白いです、
私のアプローチは、古典的な適用を使用してフラグを作成することです
df['flag']=df.apply(lambda x: 1 if 'date' in x['col_names'] else 0, axis=1)
フィルタリングした後:
df_filtered=df.loc[df['flag']==1,:]
おそらくそれらは賢いオプションが存在しますが、これはうまくいきます
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加