1

I have a data frame that looks like this:

df1

        A        Q
0   Apple    chair
1  orange     desk
2    pear  monitor
3   salad     room

df2 = df1[['Q']]

print(df2)

           Q
0      chair
1       desk
2    monitor
3       room


df2 = df2.insert(1, 'file_id_value', range(0, len(df2)))

print(df2)

Returns nothing, specifically, the word 'None'. Do you know what I am doing wrong? I am not getting an error message.

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • 2
    `insert` is an in-place operation, which returns `None`, you are assigning `None` to your DataFrame, just remove the assignment and you will be good to go! – user3483203 Aug 17 '18 at 20:02
  • Even though your question has been marked as a duplicate, you may want to check the explanation to your problem given in my answer. –  Aug 17 '18 at 20:09

1 Answers1

5

Instead of:

 df2 = df2.insert(1, 'file_id_value', range(0, len(df2)))

Do:

df2.insert(1, 'file_id_value', range(0, len(df2)))

Explanation: in Python, everything is an object. Objects are created and saved into memory. Compared to other programming languages that do variable assignment by call-by-value, Python lets you externally modify an object without the need of saving the changes into the/a new variable (as long as the object is mutable type). For that reason you can operate into df2 without needing to make the insert function return a new instance of df2. This does not always apply; for instance, string are non-mutable, so they need re-asignment.

To learn more, you may want to check out this SO question: How are Python in-place operator functions different than the standard operator functions?

Quote for mutable objects relating the addition operator:

An object's iadd method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn't have an iadd method.