Ben
Ben

Reputation: 57

How to add column and values in for loop in python with pandas?

I have a dataframe with 6 columns. And I want to add firstly one extra column to that, then use for loop to fill the value of that column.

df = pd.read_csv("/home/Datasets/custom_data/lab_data.csv") # This has 31 Rows x 6 colums

for i in range(len(df['filename'])):
    if df['region_count'][i] != 0:
        filename = df['filename'][i]
        json_acceptable_string = df['region_attributes'][i].replace("'", "\"")
        node_features_dict = json.loads(json_acceptable_string)
        center = (node_features_dict['x']+node_features_dict['width']/2, node_features_dict['y']+node_features_dict['height']/2) # center calculation

So I want to add one extra column Center to df file and fill this column with the value of center.

I tried with

data = [{'Center': center}]
    Node_label = pd.DataFrame(data)
    with open('/home/Datasets/custom_data/'+'lab_data.csv', 'a+') as csvFile: # save in .csv format
        Node_label.to_csv(csvFile, header=csvFile.tell()==0) 

But it append values in any column randomly.

Upvotes: 0

Views: 168

Answers (1)

andrzejwp
andrzejwp

Reputation: 952

You should be able to append the Center column using the concat method of pandas, read more here

Something similar to

data = [{'Center': center}]
Node_label = pd.DataFrame(data)

dfWithCenter = pd.concat([df, data], axis=1)

Upvotes: 1

Related Questions