How to add key-pair values to an open csv file?












0















I am new to Python. I have used just letters to simplify my code below.My code writes a CSV file with columns of a,b,c,d values,each has 10 rows (length). I would like to add the average value of c and d to the same CSV file as well as an additional two columns each have one row for ave values. I have tried to append field names and write the new values but it didn't work.



with open('out.csv', 'w') as csvfile:
fieldnames=['a','b','c','d']
csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
total_c=0
total_d=0
for i in range(1,length):
do something get a,b,c,d values.
total_c += c
total_d += d
csv_writer.writerow({'a': a,'b':b,'c':c,'d':d })
mean_c=total_c /length
mean_c=total_c /length


I expect to see something in the picture:



enter image description here










share|improve this question




















  • 2





    Could you show an example csv along with the expected result csv?

    – RoadRunner
    Dec 30 '18 at 4:30






  • 2





    "Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

    – Michael Butscher
    Dec 30 '18 at 4:31











  • does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

    – Mr. J
    Dec 30 '18 at 5:22











  • Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

    – kutlus
    Dec 30 '18 at 15:27











  • let me have look into it

    – Mr. J
    Jan 4 at 5:40
















0















I am new to Python. I have used just letters to simplify my code below.My code writes a CSV file with columns of a,b,c,d values,each has 10 rows (length). I would like to add the average value of c and d to the same CSV file as well as an additional two columns each have one row for ave values. I have tried to append field names and write the new values but it didn't work.



with open('out.csv', 'w') as csvfile:
fieldnames=['a','b','c','d']
csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
total_c=0
total_d=0
for i in range(1,length):
do something get a,b,c,d values.
total_c += c
total_d += d
csv_writer.writerow({'a': a,'b':b,'c':c,'d':d })
mean_c=total_c /length
mean_c=total_c /length


I expect to see something in the picture:



enter image description here










share|improve this question




















  • 2





    Could you show an example csv along with the expected result csv?

    – RoadRunner
    Dec 30 '18 at 4:30






  • 2





    "Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

    – Michael Butscher
    Dec 30 '18 at 4:31











  • does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

    – Mr. J
    Dec 30 '18 at 5:22











  • Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

    – kutlus
    Dec 30 '18 at 15:27











  • let me have look into it

    – Mr. J
    Jan 4 at 5:40














0












0








0








I am new to Python. I have used just letters to simplify my code below.My code writes a CSV file with columns of a,b,c,d values,each has 10 rows (length). I would like to add the average value of c and d to the same CSV file as well as an additional two columns each have one row for ave values. I have tried to append field names and write the new values but it didn't work.



with open('out.csv', 'w') as csvfile:
fieldnames=['a','b','c','d']
csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
total_c=0
total_d=0
for i in range(1,length):
do something get a,b,c,d values.
total_c += c
total_d += d
csv_writer.writerow({'a': a,'b':b,'c':c,'d':d })
mean_c=total_c /length
mean_c=total_c /length


I expect to see something in the picture:



enter image description here










share|improve this question
















I am new to Python. I have used just letters to simplify my code below.My code writes a CSV file with columns of a,b,c,d values,each has 10 rows (length). I would like to add the average value of c and d to the same CSV file as well as an additional two columns each have one row for ave values. I have tried to append field names and write the new values but it didn't work.



with open('out.csv', 'w') as csvfile:
fieldnames=['a','b','c','d']
csv_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
csv_writer.writeheader()
total_c=0
total_d=0
for i in range(1,length):
do something get a,b,c,d values.
total_c += c
total_d += d
csv_writer.writerow({'a': a,'b':b,'c':c,'d':d })
mean_c=total_c /length
mean_c=total_c /length


I expect to see something in the picture:



enter image description here







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 15 at 22:32









halfer

14.4k758110




14.4k758110










asked Dec 30 '18 at 4:25









kutluskutlus

5317




5317








  • 2





    Could you show an example csv along with the expected result csv?

    – RoadRunner
    Dec 30 '18 at 4:30






  • 2





    "Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

    – Michael Butscher
    Dec 30 '18 at 4:31











  • does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

    – Mr. J
    Dec 30 '18 at 5:22











  • Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

    – kutlus
    Dec 30 '18 at 15:27











  • let me have look into it

    – Mr. J
    Jan 4 at 5:40














  • 2





    Could you show an example csv along with the expected result csv?

    – RoadRunner
    Dec 30 '18 at 4:30






  • 2





    "Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

    – Michael Butscher
    Dec 30 '18 at 4:31











  • does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

    – Mr. J
    Dec 30 '18 at 5:22











  • Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

    – kutlus
    Dec 30 '18 at 15:27











  • let me have look into it

    – Mr. J
    Jan 4 at 5:40








2




2





Could you show an example csv along with the expected result csv?

– RoadRunner
Dec 30 '18 at 4:30





Could you show an example csv along with the expected result csv?

– RoadRunner
Dec 30 '18 at 4:30




2




2





"Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

– Michael Butscher
Dec 30 '18 at 4:31





"Didn't work" is a much too imprecise error description. What is the error or output, what is the expected output and behavior (edit the question to show it as properly formatted text)?

– Michael Butscher
Dec 30 '18 at 4:31













does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

– Mr. J
Dec 30 '18 at 5:22





does your csv file consist of the header? i would recommand to use python pandas to read csv file and manipulate the new columns.

– Mr. J
Dec 30 '18 at 5:22













Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

– kutlus
Dec 30 '18 at 15:27





Thank you Mr. J. Yes, i have headers they are fieldnames in my code. I tried your solution it is working but it gives a different output than i need to see,it is my bad i should have added an expected pic at the beginning. Now,I have added a picture of expected result.

– kutlus
Dec 30 '18 at 15:27













let me have look into it

– Mr. J
Jan 4 at 5:40





let me have look into it

– Mr. J
Jan 4 at 5:40












1 Answer
1






active

oldest

votes


















0














Try to use pandas library to deal with csv file. I provided sample code below, I assume that csv file has no header present on the first line.



import pandas as pd

data = pd.read_csv('out.csv',header=[['a','b','c','d'])
#making sure i am using copy of dataframe
avg_data = data.copy()

#creating new columns average in same dataframe
avg_data['mean_c'] = avg_data.iloc[:,2].mean(axis=1)
avg_data['mean_d'] = avg_data.iloc[:,3].mean(axis=1)

# writing updated data to csv file
avg_data.to_csv('out.csv', sep=',', encoding='utf-8')





share|improve this answer


























  • My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

    – kutlus
    Jan 5 at 1:04











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53975275%2fhow-to-add-key-pair-values-to-an-open-csv-file%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Try to use pandas library to deal with csv file. I provided sample code below, I assume that csv file has no header present on the first line.



import pandas as pd

data = pd.read_csv('out.csv',header=[['a','b','c','d'])
#making sure i am using copy of dataframe
avg_data = data.copy()

#creating new columns average in same dataframe
avg_data['mean_c'] = avg_data.iloc[:,2].mean(axis=1)
avg_data['mean_d'] = avg_data.iloc[:,3].mean(axis=1)

# writing updated data to csv file
avg_data.to_csv('out.csv', sep=',', encoding='utf-8')





share|improve this answer


























  • My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

    – kutlus
    Jan 5 at 1:04
















0














Try to use pandas library to deal with csv file. I provided sample code below, I assume that csv file has no header present on the first line.



import pandas as pd

data = pd.read_csv('out.csv',header=[['a','b','c','d'])
#making sure i am using copy of dataframe
avg_data = data.copy()

#creating new columns average in same dataframe
avg_data['mean_c'] = avg_data.iloc[:,2].mean(axis=1)
avg_data['mean_d'] = avg_data.iloc[:,3].mean(axis=1)

# writing updated data to csv file
avg_data.to_csv('out.csv', sep=',', encoding='utf-8')





share|improve this answer


























  • My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

    – kutlus
    Jan 5 at 1:04














0












0








0







Try to use pandas library to deal with csv file. I provided sample code below, I assume that csv file has no header present on the first line.



import pandas as pd

data = pd.read_csv('out.csv',header=[['a','b','c','d'])
#making sure i am using copy of dataframe
avg_data = data.copy()

#creating new columns average in same dataframe
avg_data['mean_c'] = avg_data.iloc[:,2].mean(axis=1)
avg_data['mean_d'] = avg_data.iloc[:,3].mean(axis=1)

# writing updated data to csv file
avg_data.to_csv('out.csv', sep=',', encoding='utf-8')





share|improve this answer















Try to use pandas library to deal with csv file. I provided sample code below, I assume that csv file has no header present on the first line.



import pandas as pd

data = pd.read_csv('out.csv',header=[['a','b','c','d'])
#making sure i am using copy of dataframe
avg_data = data.copy()

#creating new columns average in same dataframe
avg_data['mean_c'] = avg_data.iloc[:,2].mean(axis=1)
avg_data['mean_d'] = avg_data.iloc[:,3].mean(axis=1)

# writing updated data to csv file
avg_data.to_csv('out.csv', sep=',', encoding='utf-8')






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 4 at 5:45

























answered Dec 30 '18 at 5:35









Mr. JMr. J

39037




39037













  • My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

    – kutlus
    Jan 5 at 1:04



















  • My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

    – kutlus
    Jan 5 at 1:04

















My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

– kutlus
Jan 5 at 1:04





My project had a deadline and I had to find another solution-instead of adding columns, I just appended ave values end of the csv file. But thank you Mr. J for your time. This solution could have worked (if the syntax error at header (an extra square parentheses) removed)

– kutlus
Jan 5 at 1:04


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53975275%2fhow-to-add-key-pair-values-to-an-open-csv-file%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas