python pandas 插入列 [英] python pandas insert column

查看:58
本文介绍了python pandas 插入列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码以在csv文件中插入新列:

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)

当我运行代码时,没有给出错误.当我打开csv文件时,未添加新行.我决定使用python shell进行检查:

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

使用python shell,我只能在shell上看到更新的结果.如何在CSV文件中也进行更新?

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?

推荐答案

执行时-

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

它将new列插入到内存中的DataFrame df(所有值均为1000)中.它不会自动将其写回到csv.

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.

对于对数据帧所做的更改以写回到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.

这篇关于python pandas 插入列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆