Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

csv - python pandas insert column

I am writing code to insert a new column in a csv file:

import sys,os,csv,glob
dir = os.path.dirname(__file__)

import pandas as pd 

updatecsv()

def updatecsv():

    files = 'example.cs'
    df = pd.read_csv(files)
    df = df.convert_objects(convert_numeric=True)
    #until here, the code is running fine
    #now i wanted to add a new column in a specific index with all value =10           
    df.insert(2,'new',1000)

When I run the code, no error was given. When I open the csv file, the new row is not added. I decided to check using python shell:

>>>files = 'example.csv'
>>>df = pd.read_csv(files)
>>>df = df.convert_objects(convert_numeric=True)
>>>df
   A   B   C   D
0  1   2   3   4
1  5   6   7   8
2  9  10  11  12
df['new']=13
>>>df
   A   B   C   D  new
0  1   2   3   4   13
1  5   6   7   8   13
2  9  10  11  12   13
>>>df['new'] = df['new'] +1
>>>df
   A   B   C   D  new
0  1   2   3   4   14
1  5   6   7   8   14
2  9  10  11  12   14
>>>df.insert(2,'win',22)
>>>df
   A   B  win   C   D  new
0  1   2   22   3   4   14
1  5   6   22   7   8   14
2  9  10   22  11  12   14

Using the python shell, I can see the result updated on the shell only. How do I update it in the CSV file as well?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do -

df.insert(2,'new',1000)

It inserts the new column in the DataFrame df (with all values 1000) in memory. It does not automatically write it back to the csv.

For changes you did to the dataframe to be written back to csv, you should use DataFrame.to_csv() method. Example -

def updatecsv():
    files = 'example.cs'
    df = pd.read_csv(files)
    df = df.convert_objects(convert_numeric=True)
    #until here, the code is running fine
    #now i wanted to add a new column in a specific index with all value =10           
    df.insert(2,'new',1000)
    df.to_csv(files)

Also, you should make sure you define the function before you try to call it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...