Pandas DataFrame をソートするにはどうすればよいですか?

Pandas DataFrame をソートするにはどうすればよいですか?

Pandas Dataframe で並べ替えを実行できます。この記事では、さまざまな方法を使用して Pandas DataFrame を並べ替える方法について説明します。 パイソン

Pandas でのデータ フレームの並べ替え

の作成 パンダのデータフレーム デモンストレーションのために、ここではさまざまな並べ替え関数を実行するデータフレームを作成しました。

Python3




# importing pandas library> import> pandas as pd> # creating and initializing a nested list> age_list> => [[> 'Afghanistan'> ,> 1952> ,> 8425333> ,> 'Asia'> ],> > [> 'Australia'> ,> 1957> ,> 9712569> ,> 'Oceania'> ],> > [> 'Brazil'> ,> 1962> ,> 76039390> ,> 'Americas'> ],> > [> 'China'> ,> 1957> ,> 637408000> ,> 'Asia'> ],> > [> 'France'> ,> 1957> ,> 44310863> ,> 'Europe'> ],> > [> 'India'> ,> 1952> ,> 3.72e> +> 08> ,> 'Asia'> ],> > [> 'United States'> ,> 1957> ,> 171984000> ,> 'Americas'> ]]> # creating a pandas dataframe> df> => pd.DataFrame(age_list, columns> => [> 'Country'> ,> 'Year'> ,> > 'Population'> ,> 'Continent'> ])> df>

出力

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える

Pandas データフレームの並べ替え

pandasでデータフレームをソートするには、関数 並べ替え値() 使用されている。 パンダ sort_values() は、データ フレームを昇順または降順で並べ替えることができます。

Pandas DataFrame を昇順で並べ替える

コード スニペットは、「国」列に基づいて DataFrame df を昇順で並べ替えます。ただし、ソートされたデータ フレームの保存や表示は行いません。

Python3




# Sorting by column 'Country'> df.sort_values(by> => [> 'Country'> ])>

出力:

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える

Pandas DataFrame を降順で並べ替える

DataFrame df は、Population 列に基づいて降順に並べ替えられ、人口が最も多い国が DataFrame の先頭に表示されます。

Python3




# Sorting by column 'Population'> df.sort_values(by> => [> 'Population'> ], ascending> => False> )>

出力:

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える

サンプリングに基づいて Pandas データフレームを並べ替える

ここでは、DataFrame ( df> )「人口」列に基づいて、「人口」に欠損値がある行を最初に表示されるように配置します。の sort_values()> を使用したメソッド na_position='first'> 引数は、ソートされたデータフレームの先頭で欠損値を持つ行を優先してこれを実現します。

Python3




# Sorting by column 'Population'> # by putting missing values first> df.sort_values(by> => [> 'Population'> ], na_position> => 'first'> )>

出力:

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える

複数の列によるデータフレームの並べ替え

この例では、DataFrame ( df> )主に「国」列ごとに昇順で表示され、各国グループ内では「大陸」列ごとに表示されます。結果として得られる DataFrame は、指定された列の順序に基づいて並べ替えられ、並べ替えられたデータセットが作成されます。

Python3




# Sorting by columns 'Country' and then 'Continent'> df.sort_values(by> => [> 'Country'> ,> 'Continent'> ])>

出力:

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える

データフレームを列ごとに異なる順序で並べ替える

この例では、DataFrame ( df> ) 最初に「国」列が降順で表示され、各国のグループ内で「大陸」列が昇順で表示されます。結果として得られる DataFrame は、指定された列の並べ替え基準に基づいて編成されます。

Python3




# Sorting by columns 'Country' in descending> # order and then 'Continent' in ascending order> df.sort_values(by> => [> 'Country'> ,> 'Continent'> ],> > ascending> => [> False> ,> True> ])>

出力:

パンダのデータフレームを並べ替える

パンダのデータフレームを並べ替える