Charles Yeung
Charles Yeung

Reputation: 89

How to assign the values in a list to a column/row in a dataframe?

How to assign the values in a list to a column/row in python dataframe?

I could only do the vice versa with the command: list_name = df.iloc[x, y]. However, when I tried to command df.iloc[x, y] = list_name, I failed to convert the values in list_name to df.iloc[x, y].

In this case, what should be the correct command to convert the values in list_name to df.iloc[x, y]?

Upvotes: 1

Views: 2128

Answers (1)

Robin James Kerrison
Robin James Kerrison

Reputation: 1757

Unfortunately, the iloc indexing isn't designed for setting in quite as versatile a way as it is for getting. There is, however, a bit of a workaround if you want to have your row x and column y to be dynamic like in your example.

For the following, I've used the pandas.Dataframe documentation example where we're starting with a dataframe like below.

my_dict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pandas.DataFrame(my_dict)

Step 1: Get the row

Quite simply, you can get your row by taking df.iloc[x]. If you had x = 1, with the above example, we'd get:

> df.iloc[x]
a    100
b    200
c    300
d    400

When we have a row like this, we could get that value 300 by using the index 'c'.

> df.iloc[x]['c']
300

If all you have is your column index, however, you'll need to fetch this name first.

Step 2: Get the column name

To convert your index y into a column name, we can use the dataframe axes property, like follows:

> y = 2
> df.axes[1][y]
c

Step 3: Put it together

Now, if we want to use x and y to reference a particular entry in the dataframe, we can do that by first getting the row and then the column like:

row = df.iloc[x]
column = df.axes[1][y]
row[column] = desired_value

Or, if you want to one-line it:

df.iloc[x][df.axes[1][y]]

Full Example

Here's a full example of this in action.

import pandas

x = 1
y = 2

my_dict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

df = pandas.DataFrame(my_dict)

desired_value = 999

row = df.iloc[x]
column = df.axes[1][y]
row[column] = desired_value

print(df)

That print statement at the end gives us:

      a     b     c     d
0     1     2     3     4
1   100   200   999   400
2  1000  2000  3000  4000

Note the 999 we set with row[column] = desired_value.

Upvotes: 1

Related Questions