Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ コアコンテキスト Select と With_columns の比較 | パラダイムシフト、選択
Polarsによるデータ整形

コアコンテキスト Select と With_columns の比較

メニューを表示するにはスワイプしてください

PolarsのDataFrameで新しい列を作成したり、既存の列を修正したりする必要がよくあります。これに不可欠な2つのメソッドが selectwith_columns です。それぞれ異なる目的があり、使い分けを理解することで、より明確で効率的なコードを書くことができます。たとえば、games_df というDataFrameがあり、positive_reviewsnegative_reviewstotal_reviews という列があるとします。各ゲームの肯定的なレビューの割合を計算したい場合、select を使って計算結果のみを含む新しいDataFrameを作成することも、with_columns を使って既存のDataFrameに新しい列を追加することもできます。

ビデオレッスンでは、両方のアプローチのデモンストレーションが行われます。まず、select を使って positive_pct という新しい列を持つDataFrameを作成します。この列は positive_reviews / total_reviews で計算されます。

1234567891011121314151617181920212223
import polars as pl # Sample DataFrame games_df = pl.DataFrame({ "game": ["Game A", "Game B"], "positive_reviews": [80, 50], "negative_reviews": [20, 50], "total_reviews": [100, 100] }) # Using select to create a new DataFrame with only the calculated column positive_pct_df = games_df.select( (pl.col("positive_reviews") / pl.col("total_reviews")).alias("positive_pct") ) print("Result of select (only positive_pct column):") print(positive_pct_df) # Using with_columns to add a new column to the existing DataFrame games_df = games_df.with_columns( (pl.col("negative_reviews") / pl.col("total_reviews")).alias("negative_pct") ) print("\nResult of with_columns (original columns plus negative_pct):") print(games_df)

次に、with_columns を使って negative_pct のような新しい列を既存のDataFrameに追加する方法を紹介します。この列は negative_reviews / total_reviews で計算されます。

12345
# Using with_columns to add a new column to the existing DataFrame games_df = games_df.with_columns( (pl.col("negative_reviews") / pl.col("total_reviews")).alias("negative_pct") ) print(games_df)

select は指定した列のみを含む新しい DataFrame を返し、with_columns は既存の DataFrame に列を追加または更新します。この違いは、データ変換の構造を決定する際に重要です。 selectwith_columns の違いを明確にするため、以下の比較表を参照してください。この表は主な違いをまとめ、それぞれのメソッドの簡潔な例を示しています。

select を使用すると、指定した列のみを含む新しい DataFrame が作成されます。これは、特定の列や計算値のサブセットに注目したい場合に有用です。一方、with_columns は、同じ DataFrame 内で新しい列を追加したり既存の列を更新したりするのに適しており、他のすべての列を保持します。

question mark

Polars における select と with_columns の違いを最もよく表している説明はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  3
some-alt