How to calculate 10^pandas series?

Question:

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

Asked By: lwdjhfl

||

Answers:

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)
Answered By: WindCheck

You can do it directly with:

10 ** iexp
Answered By: jprebys

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})
Answered By: learner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.