How can a new column be added and assigned a value in P…

To add a new column with values in Python, you can use the DataFrame data structure from the pandas library.

For example, let’s say we have a DataFrame with names and ages.

import pandas as pd

data = {'姓名': ['张三', '李四', '王五'],
        '年龄': [20, 25, 30]}

df = pd.DataFrame(data)

To add a “gender” column and assign the value “male” to all records, you can use the following code:

df['性别'] = '男'

This will add a column “gender” to the DataFrame and assign all records a value of “male”.

To assign values to a new column based on certain logical conditions, one can use conditional statements and loops. For example, if you want to assign the value “male” to people who are 25 or older and “female” to those under 25:

df['性别'] = ''  # 先新增一列空列

for index, row in df.iterrows():
    if row['年龄'] >= 25:
        df.at[index, '性别'] = '男'
    else:
        df.at[index, '性别'] = '女'

The value of the new “gender” column will be assigned based on age conditions.

bannerAds