2
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?

More than 3 years have passed since last update.

DataFrame 行・列の追加

Last updated at Posted at 2021-07-14

#行を追加
DataFrame型のdfに対して下記を実行

df.append("Series型のデータ", ignore_index = True)
import pandas as pd

fruits = ["apple", "orange", "banana", "strawberry"]
data1 = [10, 5, 8, 12]
data2 = [30, 25, 12, 10]
data3 = [30, 12, 10, 8, 3]
series1 = pd.Series(data1, index = fruits)
series2 = pd.Series(data2, index = fruits)

fruits.append("pineapple")
series3 = pd.Series(data3, index = fruits)

df = pd.DataFrame([series1, series2])
df = df.append(series3, ignore_index = True)

df.index = ["1", "2", "3"]
display(df)

スクリーンショット 2021-07-14 21.29.21.png

#####補足
元々のカラムと追加するSeries型のデータのインデックスが一致しない場合は、値が存在しない要素にNanが埋め込まれる。

#列を追加

DataFrame型の変数dfに対して下記を実行

df["新しいカラム”] = "Seriesもしくはリスト"
import pandas as pd

fruits = ["apple", "orange", "banana", "strawberry"]
data1 = [10, 5, 8, 12]
data2 = [30, 25, 12, 10]
series1 = pd.Series(data1, index = fruits)
series2 = pd.Series(data2, index = fruits)

new_colum = pd.Series([15, 7], index = [0, 1])

df = pd.DataFrame([series1, series2])
display(df)

df["mango"] = new_colum

display(df)

スクリーンショット 2021-07-14 21.22.30.png

2
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
2
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?