Press "Enter" to skip to content

为 Pandas 数据框添加列的十种方法

我们经常需要派生或创建新的列

Photo by Austin Chan on Unsplash

DataFrame是一个带有标记行和列的二维数据结构。我们经常需要添加新的列作为数据分析或特征工程过程的一部分。

有很多不同的方法可以添加新的列。最适合您需求的方法取决于手头的任务。

在本文中,我们将学习10种将列添加到Pandas DataFrame的方法。

让我们从使用Pandas的DataFrame构造函数创建一个简单的DataFrame开始。我们将数据作为Python dictionary传递,其中列名作为字典的键,行作为字典的值。

import pandas as pd# 创建DataFramedf = pd.DataFrame(    {        "first_name": ["Jane", "John", "Max", "Emily", "Ashley"],        "last_name": ["Doe", "Doe", "Dune", "Smith", "Fox"],        "id": [101, 103, 143, 118, 128]    }   )# 显示DataFramedf
df (image by author)

1. 使用常量值

我们可以如下添加一个常量值的新列:

df.loc[:, "department"] = "engineering"# 显示DataFramedf
df (image by author)

2. 使用类似数组的结构

我们可以使用类似数组的结构添加新的列。在这种情况下,确保数组中的值的数量与DataFrame中的行数相同。

df.loc[:, "salary"] = [45000, 43000, 42000, 45900, 54000]

在上面的例子中,我们使用了Python列表。让我们使用NumPy的random模块随机确定这些值。

import numpy as npdf.loc[:, "salary"] = np.random.randint(40000, 55000, size=5)# 显示DataFramedf
Leave a Reply

Your email address will not be published. Required fields are marked *