2

I understand that i could use at to set value of particular cell robustly:

index = "a"
df.at[index,"some_list"] = []

note that loc could not be used, since

df.loc[index,"some_list"] = []

leads to the error

ValueError: Must have equal len keys and value when setting with an iterable

The problem is, sometimes, the index is not unique yet i know the exact iloc to set the value. Thus what i need to do is

df.iloc[some_number_1,some_number_2] = []

but this leads to

ValueError: Must have equal len keys and value when setting with an iterable

is there some at correspondence to iloc so that i could set the value?

For example

df.at_iloc[some_number_1,some_number_2] = []

Thank you.

Note: this question is not duplicated since i need the at variant for loc which turn out to be iat...

user40780
  • 1,828
  • 7
  • 29
  • 50

2 Answers2

2

You are looking for iat:

In [7]: df
Out[7]:
   0  1
a  1  9
b  7  7
a  2  0
c  1  8
b  6  7

In [8]: df.iat[0,1]
Out[8]: 9

You still will have to loop somehow, it's never clean working with object-dtypes and using list objects, because pandas tends to treat them like a sequence not a scalar, so something like this:

In [9]: for i, b in enumerate(df.index.get_loc('a')):
    ...:     if b:
    ...:         df.iat[i, 1] = []
    ...:

In [10]: df
Out[10]:
   0   1
a  1  []
b  7   7
a  2  []
c  1   8
b  6   7

Again, note the huge red-flag of object-dtypes:

In [18]: df.dtypes
Out[18]:
0    object
1    object
dtype: object
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
2

You must be careful to know the subtle differences between iloc and loc.
iloc maintains the implicit python-style indexing when selecting rows in a Pandas dataframe. Whereas, loc uses the explicit index of the Dataframe.

Having said that, to change the value of a dataframe record when the natural ordering using iloc is know, you can simply do:

df.iloc[some_number_1] = some_number_2

As an example,

import pandas as pd
a = pd.DataFrame({'a': [1, 3, 5, 7, 9], 'b': [2, 4, 6, 8, 0]},
                  index = [1,3,4,4,5])

   a  b
1  1  2
3  3  4
4  5  6
4  7  8
5  9  0

Assuming we want to change the values of the 1st natural index using iloc

a.iloc[1] = [12, 13]

    a   b
1   1   2
3  12  13
4   5   6
4   7   8
5   9   0
Ekaba Bisong
  • 2,918
  • 2
  • 23
  • 38
  • Yes, unfortunately, the OP is trying to insert a *list object*. I've learnd to stop arguing against that approach because it tends to fall on deaf-ears. – juanpa.arrivillaga Dec 13 '17 at 02:18