【问题标题】:python pandas insert columnpython pandas插入列
【发布时间】:2016-01-13 09:05:24
【问题描述】:

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

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 进行检查:

>>>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 文件中也更新它?

【问题讨论】:

    标签: python csv pandas


    【解决方案1】:

    当你这样做时 -

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

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

    对于您对要写回 csv 的数据帧所做的更改,您应该使用DataFrame.to_csv() 方法。示例 -

    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)
    

    此外,您应该确保在尝试调用之前定义了该函数。

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      相关资源
      最近更新 更多