जवाबों:
ज़रूर, आप उपयोग कर सकते हैं .get_loc():
In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)
In [47]: df.columns.get_loc("pear")
Out[47]: 2
हालांकि ईमानदार होने के लिए मुझे अक्सर इसकी आवश्यकता नहीं होती है। आमतौर पर नाम से पहुंच वह है जो मैं इसे ( df["pear"]और df[["apple", "orange"]], या शायद df.columns.isin(["orange", "pear"])) चाहता हूं, हालांकि मैं निश्चित रूप से ऐसे मामले देख सकता हूं जहां आप सूचकांक संख्या चाहते हैं।
insertकिसी मौजूदा कॉलम के बाद नया कॉलम चाहता हूं, तो मैं इसका उपयोग करता हूं ।
यहाँ सूची समझ के माध्यम से एक समाधान है। कोल इन इंडेक्स पाने के लिए कॉलम की सूची है:
[df.columns.get_loc(c) for c in cols if c in df]
colsकम से कम तत्व हैं df.columns, इसलिए for c in cols if c in dfकरना तेजी से होगा।
DSM का समाधान काम करता है, लेकिन अगर आप चाहते हैं कि आप के बराबर एक प्रत्यक्ष whichकर सकते हैं(df.columns == name).nonzero()
जब आप कई कॉलम मैच ढूंढ रहे होंगे, तो searchsortedविधि का उपयोग करते हुए एक वेक्टर समाधान का उपयोग किया जा सकता है। इस प्रकार, dfडेटाफ्रेम और query_colsकॉलम नामों के रूप में खोजे जाने के लिए, एक कार्यान्वयन होगा -
def column_index(df, query_cols):
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
सैंपल रन -
In [162]: df
Out[162]:
apple banana pear orange peach
0 8 3 4 4 2
1 4 4 3 0 1
2 1 2 6 8 1
In [163]: column_index(df, ['peach', 'banana', 'apple'])
Out[163]: array([4, 1, 0])
यदि आप स्तंभ स्थान से स्तंभ का नाम चाहते हैं (ओपी प्रश्न के आसपास दूसरा तरीका), तो आप उपयोग कर सकते हैं:
>>> df.columns.get_values()[location]
@DSM उदाहरण का उपयोग:
>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
>>> df.columns
Index(['apple', 'orange', 'pear'], dtype='object')
>>> df.columns.get_values()[1]
'orange'
दूसरा तरीका:
df.iloc[:,1].name
df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.)
df.columns[location]?
.ilocऑपरेटर का उपयोग करते समय कॉलम संख्या उपयोगी होती है , जहाँ आपको पंक्तियों और स्तंभों के लिए केवल पूर्णांक पास करना होगा।