Python
 Computer >> コンピューター >  >> プログラミング >> Python

Python –Pandasデータフレームに新しい列を作成します


新しい列を作成するには、作成済みの列を使用します。まず、DataFrameを作成してCSVを読みましょう-

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

次に、作成済みの列「Reg_Price」から新しい列「New_Reg_Price」を作成し、各値に100を追加して、新しい列を形成します-

dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)

以下はコードです-

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("DataFrame...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)

print("Updated DataFrame with a new column...\n",dataFrame)

print("\n[Updated] Number of rows and column in our DataFrame = ",dataFrame.shape)

出力

これにより、次の出力が生成されます-

DataFrame...
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1        Lexus         10/12/2020         750
2         Audi         10/17/2020         750
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Number of rows and column in our DataFrame = (6, 3)
Updated DataFrame with a new column ...
           Car   Date_of_Purchase   Reg_Price   New_Reg_Price
0          BMW         10/10/2020        1000            1100
1        Lexus         10/12/2020         750             850
2         Audi         10/17/2020         750             850
3       Jaguar         10/16/2020        1500            1600
4      Mustang         10/19/2020        1100            1200
5  Lamborghini         10/22/2020        1000            1100

(Updated)Number of rows and column in our DataFrame = (6, 4)

  1. Python Pandas-元のインデックスからDataFrameを作成しますが、新しいインデックスを適用します

    元のインデックスからDataFrameを作成し、新しいインデックスを適用するには、index.to_frame()を使用します。パラメータインデックスを設定します 誤りへ 。 まず、必要なライブラリをインポートします- import pandas as pd パンダインデックスの作成- index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'],name ='Products') パンダのインデックスを表示する

  2. PythonPandas-横棒グラフを作成する

    横棒グラフをプロットするには、 pandas.DataFrame.plot.barhを使用します 。棒グラフは、個別のカテゴリ間の比較を示しています。 まず、必要なライブラリをインポートします- import pandas as pd import matplotlib.pyplot as plt 4列のPandasDataFrameを作成します- dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mer