Python数据分析-数据的增加、修改和删除
补充:API参数说明
1. DataFrame.insert()
DataFrame.insert(loc, column, value, allow_duplicates=_NoDefault.no_default)
在指定位置向DataFrame插入列。
注意:如果列已经包含在DataFrame中,除非allow_duplicate设置为True,否则引发ValueError。
参数说明:
- loc:int
Insertion index. Must verify 0 <= loc <= len(columns).
- column:str, number, or hashable object
Label of the inserted column.
- value:Scalar, Series, or array-like
Content of the inserted column.
- allow_duplicates:bool, optional, default lib.no_default
Allow duplicate column labels to be created.
2. pandas.concat()
pandas.concat(objs, *, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=None)
- 沿着特定的轴连接pandas对象。
- 允许沿其他轴的可选设置逻辑。
- 还可以在连接轴上添加分层索引层,如果传递的轴号上的标签相同(或重叠)。
参数说明:
- objs:a sequence or mapping of Series or DataFrame objects
If a mapping is passed, the sorted keys will be used as the keys argument, unless it is passed, in which case the values will be selected.
- axis:{0/’index’, 1/’columns’}, default 0
The axis to concatenate along.
- join:{‘inner’, ‘outer’}, default ‘outer’
How to handle indexes on other axis (or axes).
- ignore_index:bool, default False
If True, do not use the index values along the concatenation axis. The resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join.
- keys:sequence, default None
If multiple levels passed, should contain tuples. Construct hierarchical index using the passed keys as the outermost level.
- levels:list of sequences, default None
Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys.
- names:list, default None
Names for the levels in the resulting hierarchical index.
- verify_integrity:bool, default False
Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation.
- sort:bool, default False
Sort non-concatenation axis if it is not already aligned.
- copy:bool, default True
If False, do not copy data unnecessarily.
返回值:
object, type of objs
3. DataFrame.rename()
DataFrame.rename(mapper=None, *, index=None, columns=None, axis=None, copy=None, inplace=False, level=None, errors='ignore')
- 重命名列或索引标签。
- 函数 / 字典值必须唯一(一对一)。
- 字典/系列中未包含的标签将保持原样。
- 额外列出的标签不会抛出错误。
注意:rename()方法不仅仅只有一种,还有pandas.Series.rename()和pandas.Index.rename()等等,它们的用法大同小异。
参数说明:
- mapper:dict-like or function
Dict-like or function transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper, or index and columns.
- index:dict-like or function
Alternative to specifying axis (mapper, axis=0 is equivalent to index=mapper).
- columns:dict-like or function
Alternative to specifying axis (mapper, axis=1 is equivalent to columns=mapper).
- axis:{0 or ‘index’, 1 or ‘columns’}, default 0
Axis to target with mapper. Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.
- copy:bool, default True
Also copy underlying data.
- inplace:bool, default False
Whether to modify the DataFrame rather than creating a new one. If True then value of copy is ignored.
- level:int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.
- errors:{‘ignore’, ‘raise’}, default ‘ignore’
If ‘raise’, raise a KeyError when a dict-like mapper, index, or columns contains labels that are not present in the Index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.
返回值:
DataFrame or None
引发的Error:KeyError
If any of the labels is not found in the selected axis and “errors=’raise’”.
4. DataFrame.drop()
DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')
从行或列中删除指定的标签。通过指定标签名称和相应的轴或直接指定索引或列名来删除行或列。当使用多索引时,可以通过指定级别来删除不同级别上的标签。
参数说明:
- labels:single label or list-like
Index or column labels to drop. A tuple will be used as a single label and not treated as a list-like.
- axis:{0 or ‘index’, 1 or ‘columns’}, default 0
Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).
- index:single label or list-like
Alternative to specifying axis (labels, axis=0 is equivalent to index=labels).
- columns:single label or list-like
Alternative to specifying axis (labels, axis=1 is equivalent to columns=labels).
- level:int or level name, optional
For MultiIndex, level from which the labels will be removed.
- inplace:bool, default False
If False, return a copy. Otherwise, do operation in place and return None.
- errors:{‘ignore’, ‘raise’}, default ‘raise’
If ‘ignore’, suppress error and only existing labels are dropped.
返回值:
DataFrame or None
引发的Error:KeyError
If any of the labels is not found in the selected axis.
以下是笔者在学习过程中的笔记,主要介绍各种方法对数据进行增加、修改和删除操作,仅供参考!
1. 数据集准备
1 import pandas as pd 2 3 pd.set_option('display.unicode.east_asian_width', True) # 解决数据输出时列名不对齐的问题 4 data = [[110, 105, 99], [105, 88, 115], [109, 120, 130], [112, 115, 140]] 5 name = ['Student1', 'Student2', 'Student3', 'Student4'] 6 columns = ['语文', '数学', '英语'] 7 df = pd.DataFrame(data=data, index=name, columns=columns)
2. 数据的增加
2.1. 按列增加数据
主要内容:按列增加数据、使用loc方法、使用insert方法
1 # 增加数据——按列增加数据 2 df['政治'] = [88, 79, 80, 68] 3 # 增加数据,使用loc方法 4 df.loc[:, '生物'] = [80, 89, 70, 66] 5 # 增加数据,使用insert方法 6 wl = [88, 79, 60, 50] 7 df.insert(1, '物理', wl) # 在第1列后面插入“物理”,其值为wl的数值 8 print('增加后数据:') 9 print(df) 10 11 ### 结果 12 # 增加后数据: 13 # 语文 物理 数学 英语 政治 生物 14 # Student1 110 88 105 99 88 80 15 # Student2 105 79 88 115 79 89 16 # Student3 109 60 120 130 80 70 17 # Student4 112 50 115 140 68 66
2.2. 按行增加数据——增加一行数据
1 # 按行增加数据,增加一行数据 2 df.loc['Student5'] = [100, 120, 99] 3 print('增加后数据:') 4 print(df) 5 6 ### 结果 7 # 增加后数据: 8 # 语文 数学 英语 9 # Student1 110 105 99 10 # Student2 105 88 115 11 # Student3 109 120 130 12 # Student4 112 115 140 13 # Student5 100 120 99
2.3. 按行增加数据——增加多行数据
1 # 按行增加数据,增加多行数据 2 df_insert = pd.DataFrame({'语文': [100, 123, 138], '数学': [120, 142, 60], '英语': [99, 139, 99]}, index=['Student5', 'Student6', 'Student7']) 3 # df1 = df.append(df_insert) # 此方法已经被官方移除,推荐使用concat方法 4 df1 = pd.concat([df, df_insert], axis=0) 5 print('增加后数据:') 6 print(df1) 7 8 ### 结果 9 # 增加后数据: 10 # 语文 数学 英语 11 # Student1 110 105 99 12 # Student2 105 88 115 13 # Student3 109 120 130 14 # Student4 112 115 140 15 # Student5 100 120 99 16 # Student6 123 142 139 17 # Student7 138 60 99
3. 数据的修改
3.1. 修改列索引(修改行索引方法类似)
# 修改列索引——常规方法 df.columns = ['语文', '数学(上)', '英语'] # 修改索引——使用rename方法 df.rename(columns={'语文': '语文(上)', '数学': '数学(上)', '英语': '英语(上)'}, inplace=True) ### 结果 # 修改后数据1: # 语文 数学(上) 英语 # Student1 110 105 99 # Student2 105 88 115 # Student3 109 120 130 # Student4 112 115 140 # 修改后数据2: # 语文(上) 数学(上) 英语(上) # Student1 110 105 99 # Student2 105 88 115 # Student3 109 120 130 # Student4 112 115 140
3.2. 修改整行数据
1 # 修改整行数据 2 df.loc['Student1'] = [120, 115, 109] 3 4 ### 结果 5 # 修改后数据: 6 # 语文 数学 英语 7 # Student1 120 115 109 8 # Student2 105 88 115 9 # Student3 109 120 130 10 # Student4 112 115 140 11 12 # 各科成绩均加10分 13 df.loc['Student2'] = df.loc['Student2'] + 10 14 15 # ### 结果 16 # 修改后数据: 17 # 语文 数学 英语 18 # Student1 110 105 99 19 # Student2 115 98 125 20 # Student3 109 120 130 21 # Student4 112 115 140
3.3. 修改整列数据
1 # 修改整列数据 2 df.loc[:, '语文'] = [115, 108, 112, 118] 3 4 ### 结果 5 # 修改后数据: 6 # 语文 数学 英语 7 # Student1 115 105 99 8 # Student2 108 88 115 9 # Student3 112 120 130 10 # Student4 118 115 140
3.4. 修改某一数据
1 # 修改某一数据 2 df.loc['明日', '语文'] = 115 3 4 ### 结果 5 # 修改后数据: 6 # 语文 数学 英语 7 # Student1 115 105 99 8 # Student2 105 88 115 9 # Student3 109 120 130 10 # Student4 112 115 140
3.5. 使用iloc方法修改数据
1 df.iloc[0, 0] = 115 # 修改某一数据 2 df.iloc[:, 0] = [115, 108, 112, 118] # 修改整列数据 3 df.iloc[0, :] = [120, 115, 109] # 修改整行数据
4. 数据的删除
4.1. 删除列数据
1 # 删除某列数据 2 df.drop(['数学'], axis=1, inplace=True) # 删除某列 3 4 ### 结果 5 # 修改后数据: 6 # 语文 英语 7 # Student1 110 99 8 # Student2 105 115 9 # Student3 109 130 10 # Student4 112 140 11 12 # 删除columns为“数学”的列 13 df.drop(columns='数学', inplace=True) 14 15 ### 结果 16 # 修改后数据: 17 # 语文 英语 18 # Student1 110 99 19 # Student2 105 115 20 # Student3 109 130 21 # Student4 112 140 22 23 # 删除列标签为“数学” 的列 24 df.drop(labels='数学', axis=1, inplace=True) 25 26 ### 结果 27 # 修改后数据: 28 # 语文 英语 29 # Student1 110 99 30 # Student2 105 115 31 # Student3 109 130 32 # Student4 112 140
4.2. 删除行数据
1 # 删除某行 2 df.drop(['Student1', 'Student3'], inplace=True) 3 4 ### 结果 5 # 修改后数据: 6 # 语文 数学 英语 7 # Student2 105 88 115 8 # Student4 112 115 140 9 10 # 删除index为“Student2”的行 11 df.drop(index='Student2', inplace=True) 12 13 ### 结果 14 # 修改后数据: 15 # 语文 数学 英语 16 # Student1 110 105 99 17 # Student3 109 120 130 18 # Student4 112 115 140 19 20 # 删除行标签为“Student3”的行 21 df.drop(labels='Student3', axis=0, inplace=True) 22 23 ### 结果 24 # 修改后数据: 25 # 语文 数学 英语 26 # Student1 110 105 99 27 # Student2 105 88 115 28 # Student4 112 115 140
4.3. 删除特定条件的行
1 # 删除特定条件的行 2 df.drop(index=df[df['数学'].isin([88])].index[0], inplace=True) # 删除“数学”包含88的行 3 df.drop(index=df[df['语文'] < 110].index[0], inplace=True) # 删除“语文”小于110的行 4 5 ### 结果 6 # 修改后数据: 7 # 语文 数学 英语 8 # Student1 110 105 99 9 # Student4 112 115 140
时间:2024年2月3日

Python数据分析-数据的增加、修改和删除
浙公网安备 33010602011771号