3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pandasの基本トピック

pandasの概要

pandasはデータ分析やデータの操作に用いることのできるPythonから用いることのできるオープンソースのライブラリです。統計解析に用いられるRと似たような機能を用いることができます。

pandasのインストールと動作確認

$ pip install pandas

pandasは上記を実行することでPyPIから入手することができます。

pandasの動作確認にあたっては下記などを実行すると良いです。

import pandas as pd

df1 = pd.DataFrame({'A': [1, 2, 3]})
df2 = pd.DataFrame({'A1': [1, 2, 3], 'A2': [1, 2, 3]})

print(d1)
print(d2)

・実行結果

   A
0  1
1  2
2  3
   A1  A2
0   1   1
1   2   2
2   3   3

実務でよく用いるpandasの機能

csvファイルの保存・読み込み

import pandas as pd

df = pd.DataFrame({'A1': [0.1, 0.2, 0.3], 'A2': [1, 2, 3]})

df.to_csv("sample1.csv")

上記を実行すると、下記のようなcsvファイルがカレントディレクトリに生成されます。

sample1.csv
,A1,A2
0,0.1,1
1,0.2,2
2,0.3,3

上記の一番左のインデックスを省略したい場合は下記のようにindexFalseを指定すれば良いです。

import pandas as pd

df = pd.DataFrame({'A1': [0.1, 0.2, 0.3], 'A2': [1, 2, 3]})

df.to_csv("sample2.csv", index=False)

上記を実行すると下記のようなcsvファイルがカレントディレクトリに生成されます。

sample2.csv
A1,A2
0.1,1
0.2,2
0.3,3

次にcsvファイルの読み込みについて確認します。

import pandas as pd

df = pd.read_csv("sample2.csv")

print(df)

・実行結果

    A1  A2
0  0.1   1
1  0.2   2
2  0.3   3

上記のようにread_csvメソッドを用いることでcsvファイルの読み込みを行うことができます。

カラムの追加

pandasでは辞書型に似たような表記に基づいてカラムの追加を行うことができます。カラムの追加はたとえば下記を実行することで行うことができます。

import pandas as pd

df1 = pd.read_csv("sample2.csv")
df2 = pd.read_csv("sample2.csv")
df2["A3"] = df2["A2"]**2

print(df1)
print(df2)

・実行結果

    A1  A2
0  0.1   1
1  0.2   2
2  0.3   3
    A1  A2  A3
0  0.1   1   1
1  0.2   2   4
2  0.3   3   9
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?