熊猫-用新值覆盖单列,保留其他列;覆盖原始文件

时间:2019-08-28 15:12:21

标签: python pandas

这是python的新手,我有一个包含2列的csv,我需要代码在第一列上执行简单的计算,同时保留第二列中的信息。代码当前执行计算(尽管仅在列表中的第一个csv上,并且有很多)。但是我还没有弄清楚如何在保持第二列不变的情况下覆盖每个文件中的值。我希望它使用新的计算来保存原始文件。此外,原件没有标题,而熊猫会自动分配一个数值。

import os
import pandas as pd

def find_csv(topdir, suffix='.csv'):
    filenames = os.listdir(topdir)
    csv_list = [name for name in filesnames if name.endswith(suffix)
    fp_list = []
    for csv in csv_list:
        fp = os.path.join(topdir, csv)
        fp_list.append(fp)
    return fp_list

def wn_to_um(wn):
    um = 10000/wn
    return um

for f in find_csv('C:/desktop/test'):
    readit = pd.read_csv(f, usecols=[0])
    convert = wn_to_um(readit)
    df = pd.DataFram(convert)
    df.to_csv('C:/desktop/test/whatever.csv')

3 个答案:

答案 0 :(得分:3)

我想您只需要对代码做些小的改动即可。

def wn_to_um(wn):
   wn.iloc[:,0] = 10000/wn.iloc[:,0] #performing the operation on the first column
   return wn

for f in find_csv('C:/desktop/test'):
   readit = pd.read_csv(f) #Here read the whole file
   convert = wn_to_um(readit) #while performing operation, just call the function with the second column
   os.remove(f) #if you want to replace the existing file with the updated calculation, simply delete and write
   df.to_csv('C:/desktop/test/whatever.csv')

答案 1 :(得分:1)

只需将第二个功能更新为:

df wn_to_um(wn):
    wn.iloc[:,0] = 10000/wn.iloc[:,0]
    return wn

答案 2 :(得分:1)

假设您有一个名为“ X”的列,要除以10,000。您可以将其存储为X,然后像这样将X中的每个元素分开:

X = df['X']
new_x = [X / 10000 for i in X]

从这里开始,重写数据框中的列非常简单:

df['X'] = new_x
相关问题