Annie
Annie

Reputation: 683

Select first few rows of pandas dataframe with a certain value in the column

I am trying to set values of a column in a pandas dataframe based on the value of another column,

df2.loc[df2['col1',len] == val, 'col2'] = df1['col2']

Above code works fine, however, now the problem is that I want to set values only for first few rows, something like below:

len1 = len(df1.index)
df2.loc[df2['col1',len1] == val, 'col2'] = df1['col2']

But I am getting following error:

Traceback (most recent call last):
  File "...\lib\site-packages\pandas\indexes\base.py", line 1945, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
  File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
  File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)

Any help will be highly appreciated.

Upvotes: 1

Views: 1560

Answers (1)

gold_cy
gold_cy

Reputation: 14226

Change it to this:

df2.iloc[:len(df1.index),].ix[df2.col1 == val, 'col2'] = df1['col2']

Here it is working not sure what's wrong with it.

    name gender  age occupation  years_of_school married
0    Bob      M   37    Dentist               20       N
1  Sally      F   21    Student               16       N
2    Jim      M   55  Carpenter               12       Y
3    Dan      M   27    Teacher               18       Y
4   Rose      F   14    Student                9       N
5  Emily      F   65    Retired               22       Y



  age_range
0       mid
1     young
2       old
3     young
4     young

Here is a sample query on it:

df.iloc[:len(df1.index),].ix[df.age > 25, 'occupation'] = df1['age_range']

Here is what it returns:

    name gender  age occupation  years_of_school married
0    Bob      M   37        mid               20       N
1  Sally      F   21    Student               16       N
2    Jim      M   55        old               12       Y
3    Dan      M   27      young               18       Y
4   Rose      F   14    Student                9       N
5  Emily      F   65    Retired               22       Y

I am not receiving any copying a slice errors. That might be because of the way you created or massaged your DataFrames previously but I just did this with no errors and no problems. Unless I misunderstood your original question then I don't understand why the down votes, and even then no explanation of why down voting so that I can fix it.

Upvotes: 1

Related Questions