在Python中,使用Pandas库可以很容易地对数据框(DataFrame)添加一列。以下是几种添加新列的方法:
1. 使用索引方式添加新列:
import pandas as pd创建一个DataFrame对象df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'c', 'd', 'e']})使用索引方式添加新列df['C'] = [10, 20, 30, 40, 50]打印DataFrame对象print(df)
2. 使用`assign()`方法添加新列:
import pandas as pd创建一个DataFrame对象df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'c', 'd', 'e']})使用assign()方法添加新列df = df.assign(D=[100, 200, 300, 400, 500])打印DataFrame对象print(df)

3. 使用字典的形式给DataFrame对象添加一列数据:
import pandas as pd创建一个DataFrame对象df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'c', 'd', 'e']})使用字典的形式添加新列df['C'] = [10, 20, 30, 40, 50]打印DataFrame对象print(df)
4. 使用`reindex()`方法添加一列或多列数据:
import pandas as pd创建一个DataFrame对象df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': ['a', 'b', 'c', 'd', 'e']})使用reindex()方法添加新列df = df.reindex(columns=['A', 'B', 'C'], fill_value=0)打印DataFrame对象print(df)
