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.
just use: it will select b and c column.
then u can just call df1:
I realize this question is quite old, but in the latest version of pandas there is an easy way to do exactly this. Column names (which are strings) can be sliced in whatever manner you like.
The different approaches discussed in above responses are based on the assumption that either the user knows column indices to drop or subset on, or the user wishes to subset a dataframe using a range of columns (for instance between 'C' : 'E'). pandas.DataFrame.drop() is certainly an option to subset data based on a list of columns defined by user (though you have to be cautious that you always use copy of dataframe and inplace parameters should not be set to True!!)
Another option is to use pandas.columns.difference(), which does a set difference on column names, and returns an index type of array containing desired columns. Following is the solution:
The output would be:
b c 1 3 4 2 4 5
The column names (which are strings) cannot be sliced in the manner you tried.
Here you have a couple of options. If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the
__getitem__
syntax (the []'s).Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead:
Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices).
Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. This will happen with the second way of indexing, so you can modify it with the
copy()
function to get a regular copy. When this happens, changing what you think is the sliced object can sometimes alter the original object. Always good to be on the look out for this.With pandas,
wit column names
with iloc, column index can be used like
with loc column names can be used like
hope it helps !
I am quite sure that this is not an optimized approach but can be considered as a different one.
using iterows