Home > OS >  Populate one DataFrame column from another, but every nth row value
Populate one DataFrame column from another, but every nth row value

Time:10-02

I'm trying to populate every 2nd value from a DataFrame df2 column into DataFrame df1 column using iloc, however, I'm getting alternate NULL values in the result. How do I get continuous values without the NULL values?

For example:

df1 = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': list('ABCD')})
df2 = pd.DataFrame({'col1': [2, 4, 6, 8, 10, 12, 14, 16]})

df1.col1 = df2.iloc[::2]

Output:

| col1     | col2           |
| -------- | -------------- |
|   2      |     A          |
|  NULL    |     B          |
|   6      |     C          |
|  NULL    |     D          |

Expected output:

| col1     | col2           |
| -------- | -------------- |
|   2      |     A          |
|   6      |     B          |
|   8      |     C          |
|   10     |     D          |

CodePudding user response:

Convert the Series to a list and it should work for you, likewise:

df1.col1 = df2.iloc[::2].tolist()

Output:

| col1     | col2           |
| -------- | -------------- |
|   2      |     A          |
|   6      |     B          |
|   8      |     C          |
|   10     |     D          |

CodePudding user response:

You can do:

df2.iloc[::2, :]

Which will give you:

   col1
0     2
2     6
4    10
6    14
  • Related