VBAオジサンのらくがき帳

Pandas

2021-08-08 00:00:00

初期化

import pandas as pd
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3]})
df = pd.DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["A", "B", "C"])
df = pd.DataFrame(
    [["Pinapple", 800, 1],
    ["Peach", 250, 2],
    ["Beer", 200, 12],
    ["Chicken", 1500, 1]])
df.columns = ["Item", "Price", "Qty"]
df = pd.read_csv("input.csv")
df = pd.read_csv("input.csv", header=None)
df = pd.read_csv("input.csv", names=["Item", "Price", "Qty"])

出力

print(df.head(2))
print(df.tail())
df.to_csv("out.csv")
df.to_csv("out.csv", index=False)
df.to_csv("out.csv", index=False, header=False)

データ編集

df["Qty"] = df["Qty"] + 1
df["Sale"] = False
df.sort_values(["Price"], inplace=True, ascending=False)
df.reset_index(inplace=True, drop=True)
df.loc[df["Price"] >= 500, "Qty"] = df.loc[df["Price"] >= 500, "Qty"] - 1

データ選択

df["Qty"].max()
df["Qty"].nsmallest(2)
df["Item"].to_list()
df[df["Qty"] == 1]
df[df["Qty"] == 1][["Item", "Price"]]
df.loc[df["Qty"] > 1, ["Item", "Price"]]

データの統合

df = pd.concat([df, df])
df2 = pd.DataFrame({"Item": ["Pinapple"], "Stock": [1]})
pd.merge(df, df2)
pd.merge(df, df2, how="left")
pd.merge(df, df2, on="Item", how="outer")
pd.merge(df, df2, left_on="Item", right_on="Item", how="right")