Home > Software engineering >  How to calculate 10^pandas series?
How to calculate 10^pandas series?

Time:10-20

I am trying to get a new series by calculating 10 to the power of an existing series. I have tried pandas.Series.rpow and numpy.power, but they all show strange results. Here is my code:

data = pd.read_csv('Book1.csv', sep=',', header=None, encoding='utf-8')
iexp = data.iloc[:, 9]
s = pd.Series(10, index=iexp.index)
print(s ** iexp)

Result of my code

CodePudding user response:

As @BigBen suggested, int64 is the problem here. You need to change it to a proper dtype:

df = df.astype("float")

Consider the following example:

df = pd.DataFrame({'A': [10,20,30,34],
                   'B': [10,10,10,10]})
df

output:

enter image description here

The columns have int64 dtypes:

df.dtypes

output:

enter image description here

Something similar to your code:

iexp = df.iloc[:, 0]
s = pd.Series(10, index=iexp.index)
iexp, s

output:

enter image description here

Now, the output of

print(s ** iexp)

is this:

enter image description here

As can be discerned, the int64 dtypes becomes problematic at too large numbers.

Now, change the dtype:

df = df.astype("float")

Now, the dtypes are float64 and you would get the following outputs:

enter image description here

enter image description here

Finally, note that you can change the dtype of a subset of columns as well if needed. For example to give the column A the dtype of float:

df = df.astype({"A": float})

CodePudding user response:

You can do it directly with:

10 ** iexp

CodePudding user response:

Try apply

data = pd.read_csv('Book1.csv', sep=',', header=None, encoding='utf-8')
iexp = data.iloc[:, 9]

def power_10(x):
    return 10 ** x

iexp.apply(power_10)
  • Related