How can you add a new column and assign values in pandas?

In Pandas, there are two methods available for adding a new column and assigning values.

Option 1: Using the method of direct assignment.

import pandas as pd

# 创建一个DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': ['a', 'b', 'c', 'd', 'e']}
df = pd.DataFrame(data)

# 新增一列并赋值
df['C'] = [6, 7, 8, 9, 10]

print(df)

Option 2: Utilizing the apply function.

import pandas as pd

# 创建一个DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': ['a', 'b', 'c', 'd', 'e']}
df = pd.DataFrame(data)

# 定义一个函数来赋值
def assign_value(row):
    return row['A'] * 2

# 使用apply函数新增一列并赋值
df['C'] = df.apply(assign_value, axis=1)

print(df)

You can add a new column and assign a value in a DataFrame using any method.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds