pica
pica

Reputation: 55

assignment with df.iloc() returns nan

I created a dataframe df = pd.DataFrame({'col':[1,2,3,4,5,6]}) and I would like to take some values and put them in another dataframe df2 = pd.DataFrame({'A':[0,0]})by creating new columns.

I created a new column 'B' df2['B'] = df.iloc[0:2,0] and everything was fine, but then i created another column C df2['C'] = df.iloc[2:4,0] and there were only NaN values. I don't know why and if I print print(df.iloc[2:4]) everything is normal.

full code:

import pandas as pd

df = pd.DataFrame({'col':[1,2,3,4,5,6]})
df2 = pd.DataFrame({'A':[0,0]})
df2['B'] = df.iloc[0:2,0]
df2['C'] = df.iloc[2:4,0]

print(df2)
print('\n',df.iloc[2:4])

output:

   A  B   C
0  0  1 NaN
1  0  2 NaN

    col
2    3
3    4

Upvotes: 4

Views: 1700

Answers (1)

Guillaume Jacquenot
Guillaume Jacquenot

Reputation: 11717

Assignement df2['C'] = df.iloc[2:4,0] does not work as expected, because index is not the same. You can skip this using .values attributes.

import pandas as pd

df = pd.DataFrame({'col':[1,2,3,4,5,6]})
df2 = pd.DataFrame({'A':[0,0]})
df2['B'] = df.iloc[0:2,0]
df2['C'] = df.iloc[2:4,0].values

print(df2)

Upvotes: 3

Related Questions