Home > Net >  (simple) problem with changing type and key error in Pandas
(simple) problem with changing type and key error in Pandas

Time:03-07

DataFrame

x y num
0 0 7
1 0 8
1 1 9
1 2 10
def my_function(x,y):
    print(df["num"][(df["x"] == x) & (df["y"] == y   1)])

x = my_function(1,1)
print(x)
print(type(x))

Out:
3    10
Name: num, dtype: int64
None
<class 'NoneType'>

I don't know why its becoming NoneType instead of pandas.series and how can i get "num" value here ("10")

x[0] gives key error :<

CodePudding user response:

You should be returning the value from the function like below code.

def my_function(x,y):
    print(df["num"][(df["x"] == x) & (df["y"] == y   1)])
    return df["num"][(df["x"] == x) & (df["y"] == y   1)]

x = my_function(1,1)
print(x)
print(type(x))

print(x.index.values)
print(x[3])

# Output below
3    10
Name: num, dtype: int64
3    10
Name: num, dtype: int64
<class 'pandas.core.series.Series'>
[3]
10

The series which the function is returning, has index value - 3 only hence the key error when you pass 0. pass 3 instead like in above code it will work

  • Related