Set values in DataFrame together for specific indices and specific columns

Question:

I am trying to set values in DataFrame for a set of indices and columns at the same time, but I am getting None values.

Here is my code:

import pandas as pd
results = pd.DataFrame({0: ['a', 'b', 'c'], 1: ['e', 'f', 'g']})
data = pd.DataFrame({'id': [i for i in range(10)], 'top1': [i*2 for i in range(10)], 'top2': [i*3 for i in range(10)]})
at_index = np.array([0,1,2])

### I tried all of those ways but none of them worked.
data.loc[at_index, ["top1", "top2"]] = results
# data[["top1", "top2"]].iloc[at_index] = results
# data.iloc[at_index][["top1", "top2"]] = results    

enter image description here

Asked By: Minions

||

Answers:

You cannot have more than one data type in the same column of a dataframe

Answered By: Eat Ing

Problem is that the column name of results and target top1, top2 are not the same. You can try assign numpy array

data.loc[at_index, ["top1", "top2"]] = results.values # or results.to_numpy()
print(data)

   id top1 top2
0   0    a    e
1   1    b    f
2   2    c    g
3   3    6    9
4   4    8   12
5   5   10   15
6   6   12   18
7   7   14   21
8   8   16   24
9   9   18   27
Answered By: Ynjxsjmh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.