Saturday, 15 March 2014

python - Pandas Dataframe row by row fill new column -



python - Pandas Dataframe row by row fill new column -

i trying perform row row operation on pandas dataframe such:

df = pd.dataframe(columns=['product', 'price', 'buy', 'sell']) df.loc[len(df.index)] = ["apple", 1.50, 3, 2] df.loc[len(df.index)] = ["banana", 0.75, -8, 4] df.loc[len(df.index)] = ["carrot", 2.00, -6, -3] df.loc[len(df.index)] = ["blueberry", 0.05, 5, 6]

basically want create new column "ratio" divides price/buy or price/sell, depending on abs(buy) or abs(sell) greater. not sure how this...would utilize apply function?

thanks!

you can straight utilize column indexing (http://pandas.pydata.org/pandas-docs/stable/indexing.html) compare , filter ratios.

buy_ratio = (abs(df["buy"]) > abs(df["sell"])) * df["price"] / df["buy"] sell_ratio = (abs(df["buy"]) <= abs(df["sell"])) * df["price"] / df["sell"] df["ratio"] = buy_ratio + sell_ratio

in case,

the status (abs(df["buy"]) > abs(df["sell"])) gives 0/1 valued column depending on whether purchase or sell greater. multiply column price/buy. if sell cost high, multiplication zero. perform symmetric operation sell finally, add together them , straight set column named "ratio" using indexing.

edit

here solution using apply - first define function operating in rows of dataframe.

def f(row): if abs(row["buy"]) > abs(row["sell"]): homecoming row["price"] / row["buy"] else: homecoming row["price"] / row["sell"]

finally, set ratio column appropriately using apply.

df["ratio"] = df.apply(f, axis=1)

python pandas dataframes apply

No comments:

Post a Comment