【549】pandas小技巧
参考:python pandas中 inplace 参数理解
1. 删除指定列 or 行
- Drop specified labels from rows or columns.
- 删除指定的行列信息。
- df.drop(columns=["name"], inplace=True)
- 默认 inplace 为 False,会新建一个对象(原对象不变)
- 若 inplace 设置为 True,则原对象进行处理
- 参考:https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.DataFrame.drop.html
# 首先获取等于 0 的 dataframe # 然后获取其 index,就是一个 list # 然后删掉对应部分 opt_df.drop(opt_df[opt_df['solution_value'] == 0].index, inplace=True)
2. 通过 apply 增加新列
- df["name"].apply(lambda item: "Mr. " + item) # 相当于名字前面加上前缀
- Apply a function along an axis of the DataFrame.
- 沿着 DataFrame 的某个轴的方向通过函数处理(可以不用频繁遍历了)
- 参考:https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.DataFrame.apply.html
- func : function
- Function to apply to each column or row.
- axis : {0 or ‘index’, 1 or ‘columns’}, default 0
- Axis along which the function is applied:
- 0 or ‘index’: apply function to each column.
- 1 or ‘columns’: apply function to each row.
3. 增加新行
- 通过获取最后一列的索引
- df.loc[i] = ... 来实现
4. 通过多个 list 创建 dataframe
- 需要通过 matrix 在中间过渡一下
- 不过主要 matrix 需要做个 transpose
matrix = np.matrix([model, precision, recall, F1]) df_metrics = pd.DataFrame(data=matrix.transpose(), columns=['model', 'precision', 'recall', 'F1'])