如何获取数据框中列的位置编号

时间:2014-07-28 15:41:20

标签: python pandas

我对pandas数据框和列有一个看似简单的问题。假设我有一个带有列的DF:

索引([' _ArtNameName',' _BasePrice',' _Category',' _CategoryName',' _DPEffectAdh' ,' _DPEffectFLAG_AFFAIRES_FNAC',#DPEffectFin',' _DPEffectOff',' _DPEffectOpe',' _DPEffectSol',' _FountQuantity',' _LatestBasePrice',' _Method',' _OptPrice',' _OptQuantity',' _OwnPriceElasticity', ' _PriceLowerBound' _&_39; _PriceUpperBound' _QualityIndi​​cator',' _Quantity',' _Segment',' _SegmentName& #39;,' _StatusEstim',' _SuccessOptim',' _TaxRate',' _UnitCost',' _StatusOptim'], D型='对象&#39)

如何获得说' _BasePrice'的列位置,例如2,' _CategoryName',例如4等? 谢谢!

1 个答案:

答案 0 :(得分:1)

使用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

请注意,索引值是从零开始的