如何在 Python 中向現有的 DataFrame 新增新列?


DataFrame 是一種二維資料結構,其中資料以表格格式儲存,以行和列的形式表示。

它可以被視為 SQL 資料表或 Excel 表格的表示形式。它可以使用以下建構函式建立:

pd.Dataframe(data, index, columns, dtype, copy)

可以透過不同的方式向 DataFrame 新增新列。

讓我們看看其中一種方法,即首先建立一個 Series 資料結構,然後將其作為附加列傳遞到現有的 DataFrame 中。

讓我們看看程式碼的實際操作:

示例

 線上演示

import pandas as pd
my_data = {'ab' : pd.Series([1, 8, 7], index=['a', 'b', 'c']),
'cd' : pd.Series([1, 2, 0, 9], index=['a', 'b', 'c', 'd'])}
my_df = pd.DataFrame(my_data)
print("The dataframe is :")
print(my_df)
print ("Adding a new column to the dataframe by passing it as a Series structure :")
my_df['ef']=pd.Series([56, 78, 32],index=['a','b','c'])
print("After adding a new column to the dataframe, :")
print(my_df)

輸出

The dataframe is :
   ab   cd
a  1.0  1
b  8.0  2
c  7.0  0
d  NaN  9
Adding a new column to the dataframe by passing it as a Series structure :
After adding a new column to the dataframe, :
    ab  cd  ef
a  1.0  1   56.0
b  8.0  2  78.0
c  7.0  0  32.0
d  NaN  9  NaN

解釋

  • 匯入所需的庫,併為方便使用賦予別名。

  • 建立一個字典資料結構,其中一個字典中存在鍵值對。

  • 以此方式,建立多個字典並存儲在列表中。

  • 鍵值對中的“value”實際上是 Series 資料結構。

  • 索引也是一個自定義的值列表。

  • 稍後將此字典作為引數傳遞給“pandas”庫中存在的“DataFrame”函式

  • 透過將字典值的列表作為引數傳遞給它來建立 DataFrame。

  • 建立另一個新列並在其中初始化值。

  • 此新列被索引到原始 DataFrame。

  • 這樣,新列就被繫結到 DataFrame。

  • DataFrame 在控制檯上列印。

注意 - “NaN” 代表“非數字”,這意味著特定 [行,列] 值沒有任何有效條目。

更新於: 2020-12-10

180 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.