pandas.DataFrame.insert#
- DataFrame.insert(loc, column, value, allow_duplicates=_NoDefault.no_default)[源代码]#
在指定位置将列插入DataFrame。
如果 column 已存在于 DataFrame 中,则引发 ValueError,除非 allow_duplicates 设置为 True。
- Parameters:
- locint
插入索引。必须满足 0 <= loc <= len(columns)。
- columnstr, number, or hashable object
插入列的标签。
- valueScalar, Series, or array-like
插入列的内容。
- allow_duplicatesbool, optional, default lib.no_default
允许创建重复的列标签。
参见
Index.insert按索引插入新项。
Examples
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df col1 col2 0 1 3 1 2 4 >>> df.insert(1, "newcol", [99, 99]) >>> df col1 newcol col2 0 1 99 3 1 2 99 4 >>> df.insert(0, "col1", [100, 100], allow_duplicates=True) >>> df col1 col1 newcol col2 0 100 1 99 3 1 100 2 99 4
请注意,在 value 类型为 Series 的情况下,pandas 会使用索引对齐:
>>> df.insert(0, "col0", pd.Series([5, 6], index=[1, 2])) >>> df col0 col1 col1 newcol col2 0 NaN 100 1 99 3 1 5.0 100 2 99 4