如何在 Python 的 Pandas 庫中以列表的形式存取 DataFrame 列和行?

Mary-Kate Olsen
發布: 2024-10-26 17:13:30
原創
600 人瀏覽過

How do you access DataFrame columns and rows as lists in Python's Pandas library?

以列表形式存取 DataFrame 列和行

在 Python 的 Pandas 庫中,DataFrame 包含表格資料的行和列。若要存取DataFrame 列或行的內容,可以使用以下方法:

1.取得列內容

要將DataFrame 欄位的內容作為清單檢索,請在表示在該列的Series 物件上使用tolist() 方法。您也可以使用 list() 函數將系列轉換為清單。

<code class="python">import pandas as pd

# Create a DataFrame from sample data
df = pd.DataFrame({
    'cluster': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
    'load_date': ['1/1/2014', '2/1/2014', '3/1/2014', '4/1/2014', '4/1/2014', '4/1/2014', '7/1/2014', '8/1/2014', '9/1/2014'],
    'budget': [1000, 12000, 36000, 15000, 12000, 90000, 22000, 30000, 53000],
    'actual': [4000, 10000, 2000, 10000, 11500, 11000, 18000, 28960, 51200],
    'fixed_price': ['Y', 'Y', 'Y', 'N', 'N', 'N', 'N', 'N', 'N']
})

# Convert column values to a list
cluster_list = df['cluster'].tolist()

# Alternatively, you can cast the Series to a list
cluster_list = list(df['cluster'])</code>
登入後複製

2.取得行內容

要以列表形式取得 DataFrame 行的內容,請使用 loc 或 iloc 存取器以及適當的行索引。

<code class="python"># Get row 1 as a list using 'loc'
row_1_list = df.loc[0].tolist()

# Get row 1 as a list using 'iloc'
row_1_list = df.iloc[0].tolist()</code>
登入後複製

範例輸出:

cluster_list: ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
row_1_list: [1000, 4000, 'Y']
登入後複製

以上是如何在 Python 的 Pandas 庫中以列表的形式存取 DataFrame 列和行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!