I have a seemingly simple (?) question on pandas data frames and columns. Say I have a DF with columns :
Index(['_ArticleName', '_BasePrice', '_Category', '_CategoryName', '_DPEffectAdh', '_DPEffectFLAG_AFFAIRES_FNAC', '_DPEffectFin', '_DPEffectOff', '_DPEffectOpe', '_DPEffectSol', '_FittedQuantity', '_LatestBasePrice', '_Method', '_OptPrice', '_OptQuantity', '_OwnPriceElasticity', '_PriceLowerBound', '_PriceUpperBound', '_QualityIndicator', '_Quantity', '_Segment', '_SegmentName', '_StatusEstim', '_SuccessOptim', '_TaxRate', '_UnitCost', '_StatusOptim'], dtype='object')
How do I get the column position of say '_BasePrice', eg 2, '_CategoryName', eg 4, etc? Thanks!
Use get_loc
:
In [46]:
df = pd.DataFrame({'B':randn(5), 'A':randn(5), 'F':randn(5), 'D':randn(5)})
df.columns
Out[46]:
Index(['A', 'B', 'D', 'F'], dtype='object')
In [47]:
df.columns.get_loc('D')
Out[47]:
2
In [48]:
df = pd.DataFrame(columns=['_ArticleName', '_BasePrice', '_Category', '_CategoryName', '_DPEffectAdh', '_DPEffectFLAG_AFFAIRES_FNAC', '_DPEffectFin', '_DPEffectOff', '_DPEffectOpe', '_DPEffectSol', '_FittedQuantity', '_LatestBasePrice', '_Method', '_OptPrice', '_OptQuantity', '_OwnPriceElasticity', '_PriceLowerBound', '_PriceUpperBound', '_QualityIndicator', '_Quantity', '_Segment', '_SegmentName', '_StatusEstim', '_SuccessOptim', '_TaxRate', '_UnitCost', '_StatusOptim'])
df.columns
Out[48]:
Index(['_ArticleName', '_BasePrice', '_Category', '_CategoryName', '_DPEffectAdh', '_DPEffectFLAG_AFFAIRES_FNAC', '_DPEffectFin', '_DPEffectOff', '_DPEffectOpe', '_DPEffectSol', '_FittedQuantity', '_LatestBasePrice', '_Method', '_OptPrice', '_OptQuantity', '_OwnPriceElasticity', '_PriceLowerBound', '_PriceUpperBound', '_QualityIndicator', '_Quantity', '_Segment', '_SegmentName', '_StatusEstim', '_SuccessOptim', '_TaxRate', '_UnitCost', '_StatusOptim'], dtype='object')
In [49]:
df.columns.get_loc('_BasePrice')
Out[49]:
1
In [50]:
df.columns.get_loc('_CategoryName')
Out[50]:
3
Note that index values are zero-based
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.