Sayed Gouda
Sayed Gouda

Reputation: 615

python pandas replace all the float values

The purpose of this code is to:

  1. create a dummy data set.
  2. Then turn it into a data frame
  3. Calculate the peaks and make it a column in the data frame
  4. Calculate the troughs and make it a column in the data frame
  5. Filling the “nan” values with “hold”
  6. Replace all the float values with the word “buy”

The problem is with last step is that it is never worked, but there is no error, it is just print the dataframe just like before this couple of lines.

Here is the code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema

list1 = np.random.randint(0,30,(25,2))
df = pd.DataFrame(list1, columns=['a', 'b'])

df['minimum']= df.b[(df.b.shift(1) > df.b) & (df.b.shift(-1) > df.b)]
df['maximum'] = df.b[(df.b.shift(1) < df.b) & (df.b.shift(-1) < df.b)]

plt.scatter(df.index, df['minimum'], c='g')
plt.scatter(df.index, df['maximum'], c='r')
df.b.plot(figsize=(15,5))

df['minimum'].fillna('hold', inplace = True)
for x in df['minimum']:
  if type(x) =='float':
    df['minimum'].replace(x, 'buy', inplace = True)
print('df')

Upvotes: 1

Views: 1069

Answers (2)

Varun Singh
Varun Singh

Reputation: 519

np.where is a good idea You can also do

df.loc[~df['minimum'].isna(),'minimum']='Buy'
df.loc[df['minimum'].isna(),'minimum']='Hold'

Upvotes: 1

Pawan Jain
Pawan Jain

Reputation: 825

Use np.where to classify it

df['minimum'] = (np.where(df['minimum'].isnull(), 'hold', 'buy'))

Upvotes: 3

Related Questions