Skip to content
Advertisement

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

I have two dataframes as follows:

leader:

JavaScript

DatasetLabel:

JavaScript

The Information dataset column names 0 to 6 are DatasetLabel about data and 7 to 12 are indexes that refer to the first column of leader Dataframe.

I want to create dataset where instead of the indexes in DatasetLabel dataframe, I have the value of each index from the leader dataframe, which is leader.iloc[index,1].

How can I do it using python features?

The output should look like:

DatasetLabel:

JavaScript

I have come up with the following, but I get an error:

JavaScript

Error:

JavaScript

Advertisement

Answer

You can use apply to index into leader and exchange values with DatasetLabel, although it’s not very pretty.

One issue is that Pandas won’t let us index with NaN. Converting to str provides a workaround. But that creates a second issue, namely, column 9 is of type float (because NaN is float), so 5 becomes 5.0. Once it’s a string, that’s "5.0", which will fail to match the index values in leader. We can remove the .0, and then this solution will work – but it’s a bit of a hack.

With DatasetLabel as:

JavaScript

And leader as:

JavaScript

Then:

JavaScript

Now we can concat the unmodified columns (which we’ll call original) with updated:

JavaScript

Output:

JavaScript

Note: It may be clearer to use concat here, but here’s another, cleaner way of merging original and updated, using assign:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement