Stanko
Stanko

Reputation: 4475

Change values of a row with certain index

I have this table:

table

For example: I just want to update the values (except stream) of the row with index a.

The things I tried:

index = 'a'
cols = [col for col in df.columns if col != 'stream']
df.loc[index,cols] = df * some_value

This gave me the error: ValueError: Incompatible indexer with DataFrame

Then I just tried:

index = 'a'
df.loc[index] = df * some_value

But that I also gave me the same error.

At last I also tried:

df.index.name = 'foo'
cols = [col for col in df.columns if col != 'stream']
df.loc[df['foo'] == 'a', cols ] = df * some_value

But that was also unsuccessful. How do I handle this?

Upvotes: 1

Views: 127

Answers (2)

jezrael
jezrael

Reputation: 863531

I think you need add []:

index = ['a']
cols = [col for col in df.columns if col != 'stream']

df.loc[index, cols] = df * some_value

Sample:

print df
   stream  feat  another_feat
a       1     1             4
b       2     2             5
c       2     5             1
d       3     3             4

some_value = 5

index = ['a']
cols = [col for col in df.columns if col != 'stream']

df.loc[index,cols] = df * some_value
print df
   stream  feat  another_feat
a       1     5            20
b       2     2             5
c       2     5             1
d       3     3             4

It works, because it return DataFrame (thanks ayhan):

print df.loc[['a'],cols]
   feat  another_feat
a     1             4

print df.loc['a',cols]
feat            1
another_feat    4
Name: a, dtype: int64

EDIT: Another solution:

cols = [col for col in df.columns if col != 'stream']

df.loc['a',cols] = df.loc['a',cols] * some_value
print df
   stream  feat  another_feat
a       1     5            20
b       2     2             5
c       2     5             1
d       3     3             4

Upvotes: 1

firelynx
firelynx

Reputation: 32234

Sounds like you want the .loc operator

In [3]: df
Out[3]: 
   stream  feat  another_feat
a       1     1             4
b       2     2             5
c       2     5             1
d       3     3             4

In [4]: df.loc['a', 'feat'] = 'foobar'

In [5]: df
Out[5]: 
   stream    feat  another_feat
a       1  foobar             4
b       2       2             5
c       2       5             1
d       3       3             4

It also works on multiple columns

In [6]: df.loc['a', ['feat', 'another_feat']] = ['foo', 'bar']

In [7]: df
Out[7]: 
   stream feat another_feat
a       1  foo          bar
b       2    2            5
c       2    5            1
d       3    3            4

Sorting out "all the columns but the 'steam' column" can easily enough be done by:

columns = list(df.columns)
columns.remove('steam')

Which in my opinion is much more clean and clear than a one-liner list function.

Readability counts - The Zen of Python

Upvotes: 2

Related Questions