pandas.DataFrame.insert#
- DataFrame.insert(loc, column, value, allow_duplicates=NoDefault.no_default)[源代码]#
在DataFrame中的指定位置插入列。
如果发生以下情况,则引发ValueError column 已包含在DataFrame中,除非 allow_duplicates 设置为True。
- 参数
- loc集成
插入索引。必须验证0<=loc<=len(列)。
- column字符串、数字或可哈希对象
插入的列的标签。
- value标量、系列或类似数组
- allow_duplicatesBool,可选,默认lib.no_default
参见
Index.insert
按索引插入新项目。
示例
>>> 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
请注意,Pandas在以下情况下使用索引对齐 value From类型 Series :
>>> 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