数据帧
|new_0_cost|new_0_quantity|new_2_cost|new_2_quantity|quality|weights| 0| 10 | 20 | 10 | 20 | good | 40 |
功能
def drop_cost_and_quan(data): # data is a dataframe described above # try to drop new_cost0,new_2_cost,and new_2_quantity data3 = data.copy() for i,item in enumerate(data3.columns): if item == 'new_{0}_cost'.format(i): data3 = data3.drop(item,axis=1) print('cost:',item == 'new_{0}_cost'.format(i)) for i,item in enumerate(data3.columns): if item == 'new_{0}_quantity'.format(i): data3 = data3.drop(item,axis=1) print(item == 'item_{0}_quantity'.format(i)) return data3
Outptut:
data3 = drop_cost_and_quan(data):cost: Truecost: Falsecost: Truecost: Falsecost: Falsecost: Falsequntity: Truequntity: Falsequntity: Falsequntity: Falsedata3 |new_2_quantity|quality| weights|0| 20 |good |40解决方法 或者@ vinod的方法你也可以这样做:
In [148]: dfOut[148]: new_0_cost new_0_quantity new_2_cost new_2_quantity new_0_total_cost new_2_total_cost quality weights0 10 20 10 20 1111 2222 good 40In [151]: df.drop(df.columns[df.columns.str.contains(r'^new_\d+_(?:quantity|cost)')],1,inplace=True)In [152]: dfOut[152]: new_0_total_cost new_2_total_cost quality weights0 1111 2222 good 40
说明:
In [148]: dfOut[148]: new_0_cost new_0_quantity new_2_cost new_2_quantity new_0_total_cost new_2_total_cost quality weights0 10 20 10 20 1111 2222 good 40In [149]: df.columns.str.contains(r'^new_\d+_(?:quantity|cost)')Out[149]: array([ True,True,False,False],dtype=bool)In [150]: df.columns[df.columns.str.contains(r'^new_\d+_(?:quantity|cost)')]Out[150]: Index(['new_0_cost','new_0_quantity','new_2_cost','new_2_quantity'],dtype='object')总结
以上是内存溢出为你收集整理的Python格式和熊猫全部内容,希望文章能够帮你解决Python格式和熊猫所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)