python pandas insert column

后端 未结 1 456
栀梦
栀梦 2020-12-19 07:28

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 update         


        
相关标签:
1条回答
  • 2020-12-19 07:42

    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.

    0 讨论(0)
提交回复
热议问题