简体   繁体   中英

Pandas .ix Example from Pandas for Data Analysis, rewritten

I'm a newbie trying to go through Python for Data Analysis. I've been able to follow along and think Pandas is fantastic.

However, the example on page 127 uses the deprecated .ix method and I've tried to rework it a couple of times and am stumped.

Primarily I referenced the thorough explanation here: How are Pandas iloc, ix and loc different and related?

Specifically the section titled 'Simultaneous selection with labels and integer location'

Here's the example in the book:

data = DataFrame(np.arange(16).reshape((4, 4)),
 index=['Ohio', 'Colorado', 'Utah', 'New York'],
columns=['one', 'two', 'three', 'four'])

[In]: data.ix[['Colorado', 'Utah'], [3, 0, 1]]
[Out]:
four one two
Colorado 7 0 5
Utah 11 8 9

And here's my example, based of the SO article, that I can't get to work:

labels = ['Colorado','Utah']
ind_names = data.index.get_loc()
index_ints = [df.index.get_loc(label) for label in labels]
print(data.iloc[index_ints,[3,0,1]])

Thank you for your help.

You need change df to data in list comprehension:

labels = ['Colorado','Utah']

index_ints = [data.index.get_loc(label) for label in labels]
print(data.iloc[index_ints,[3,0,1]])
          four  one  two
Colorado     7    4    5
Utah        11    8    9

Or use Index.get_indexer for positions by index names:

print(data.iloc[data.index.get_indexer(labels),[3,0,1]])
#alternatives
#print(data.iloc[data.index.searchsorted(labels),[3,0,1]])
          four  one  two
Colorado     7    4    5
Utah        11    8    9

Detail :

print(data.index.get_indexer(labels))
[1 2]

您可以通过loc使用基于标签的索引:

data.loc[['Colorado', 'Utah'], data.columns[[3, 0, 1]]]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM