alex_bn_lee

导航

【549】pandas小技巧

参考:python pandas中 inplace 参数理解

参考:【pandas】删除满足条件元素所在的行


 1. 删除指定列 or 行

# 首先获取等于 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'])

 

posted on 2021-04-12 16:53  McDelfino  阅读(94)  评论(0)    收藏  举报