📅  最后修改于: 2020-10-29 01:49:36             🧑  作者: Mango
Assign()方法还负责将新列添加到DataFrame中。
如果我们重新分配一个现有的列,则其值将被覆盖。
DataFrame.assign(**kwargs)
它返回带有新列的新DataFrame。
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
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