本文概述
Assign()方法还负责将新列添加到DataFrame中。
如果我们重新分配一个现有的列, 则其值将被覆盖。
签名
DataFrame.assign(**kwargs)
参数
- kwargs:关键字是列名。如果这些值是可调用的, 则将这些关键字分配给新列。如果值是不可调用的, 则只分配它们。
退货
它返回带有新列的新DataFrame。
范例1:
import pandas as pd
# Create an empty dataframe
info = pd.DataFrame()
# Create a column
info['ID'] = [101, 102, 103]
# View the dataframe
info
# Assign a new column to dataframe called 'age'
info.assign(Name = ['Smith', 'Parker', 'John'])
输出
ID Name
0 101 Smith
1 102 Parker
2 103 John
范例2:
import pandas as pd
# Create a dataframe
info = pd.DataFrame({'temp_c': [17.0, 25.0]}, # Create an index that consist some values
index=['Canada', 'Australia'])
# View the dataframe
info
info.assign(temp_f=lambda x: x.temp_c * 7 / 2 + 24)
info.assign(temp_f=lambda x: x['temp_c'] * 6 / 2 + 21, temp_k=lambda x: (x['temp_f'] + 342.27) * 6 / 4)
输出
temp_c temp_f temp_k
Canada 17.0 72.0 621.405
Australia 25.0 96.0 657.405
来源:
https://www.srcmini02.com/30920.html