向 Python Pandas 中的现有 DataFrame 添加新列
要将新列添加到现有DataFrame,我们只需创建一个列并为其分配与其他列相同行数的值。
步骤
创建二维、大小可变、潜在异构的表格数据df。
打印输入数据帧。
创建一个新列a,并为该列赋值。
打印数据帧,df。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:\n", df
df['a'] = [2, 4, 1, 0]
print "After adding new column:\n", df输出结果Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 After adding new column: x y z a 0 5 4 4 2 1 2 1 1 4 2 1 5 5 1 3 9 10 0 0