csv - python pandas insert column -


i writing code insert new column in csv file:

import sys,os,csv,glob dir = os.path.dirname(__file__)  import pandas pd   updatecsv()  def updatecsv():      files = 'example.cs'     df = pd.read_csv(files)     df = df.convert_objects(convert_numeric=true)     #until here, code running fine     #now wanted add new column in specific index value =10                df.insert(2,'new',1000) 

when run code, no error given. when open csv file, new row not added. decided check using python shell:

>>>files = 'example.csv' >>>df = pd.read_csv(files) >>>df = df.convert_objects(convert_numeric=true) >>>df      b   c   d 0  1   2   3   4 1  5   6   7   8 2  9  10  11  12 df['new']=13 >>>df      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      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      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 python shell, can see result updated on shell only. how update in csv file well?

when -

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

it inserts new column in dataframe df (with values 1000) in memory. not automatically write csv.

for changes changes did dataframe written csv, 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, code running fine     #now wanted add new column in specific index value =10                df.insert(2,'new',1000)     df.to_csv(files) 

also, should make sure define function before try call it.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -