srgam
srgam

Reputation: 366

How to make operations within each columns value of a pd.Dataframe?

I have a pandas Dataframe, and I want to write into a the column 'final_data['130 + 71444']' the result after make for each value inside the cells the following math operation:

final = pd.read_csv(path, header=0, parse_dates=True, index_col="Tagname")
final_data = pd.DataFrame(final)

enter image description here


Edited: I tried:

final_data['130 + 71444'] = (final_data['130.c'] + final_data['7144.c'])/final_data['c']

But the following error is displayed:

TypeError: unsupported operand type(s) for /: 'str' and 'str'

How can I do it?

Upvotes: 1

Views: 63

Answers (2)

coco18
coco18

Reputation: 1085

It is easy. It is like you defined: EDIT First you have to change the dtype of the columns. I am using here float.

final_data['130.c'] = final_data['130.c'].astype('float32')
final_data['7144.c'] = final_data['7144.c'].astype('float32')
final_data['c'] = final_data[c'].astype('float32')


final_data['130 + 71444'] = (final_data['130.c'] + final_data['7144.c'])/final_data['c']

this is possible, because you have numpy array as column in your data frame. See also the docs of pandas and numpy .

Upvotes: 0

jezrael
jezrael

Reputation: 862591

Use:

final_data['130 + 71444'] = (final_data['130.c'].astype(float) + final_data['7144.c'].astype(float))/final_data['c'].astype(float)

If not working code above because some non numeric values use to_numeric with erriors='coerce' for convert these values to missing values:

final_data['130 + 71444'] = (pd.to_numeric(final_data['130.c'], errors='coerce') + pd.to_numeric(final_data['7144.c'], errors='coerce') )/pd.to_numeric(final_data['c'], errors='coerce') 

Upvotes: 1

Related Questions