Selecting multiple columns in a pandas dataframe

2018-12-31 15:30发布

I have data in different columns but I don't know how to extract it to save it in another variable.

index  a   b   c
1      2   3   4
2      3   4   5

How do I select 'a', 'b' and save it in to df1?

I tried

df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']

None seem to work.

14条回答
像晚风撩人
2楼-- · 2018-12-31 16:02

If you want to get one element by row index and column name, you can do it just like df['b'][0]. It is as simple as you can image.

Or you can use df.ix[0,'b'],mixed usage of index and label.

Note: Since v0.20 ix has been deprecated in favour of loc / iloc.

查看更多
大哥的爱人
3楼-- · 2018-12-31 16:02

Starting in 0.21.0, using .loc or [] with a list with one or more missing labels, is deprecated, in favor of .reindex. So, the answer to your question is:

df1 = df.reindex(columns=['b','c'])

In prior versions, using .loc[list-of-labels] would work as long as at least 1 of the keys was found (otherwise it would raise a KeyError). This behavior is deprecated and now shows a warning message. The recommended alternative is to use .reindex().

Read more at https://pandas.pydata.org/pandas-docs/stable/indexing.html#reindexing

查看更多
登录 后发表回答