0

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.

1
  • 3
    Please share a mcve Commented Jan 16, 2020 at 18:47

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.