【问题标题】:Filling a column with data obtained by comparing data from another column用通过比较另一列的数据获得的数据填充一列
【发布时间】:2017-09-07 23:24:48
【问题描述】:

我有一张桌子。我正在创建一个新列“时间”。我需要用数字填充它,具体取决于“类型”列中的数据。例如,如果在“type”列的单元格中是dgv,那么在“timing”列中应该有一个数字17,如果ds,那么8,如果psp,那么3,等等。总共有几个条件.

part of the table 等等

我的代码:

import csv

with open('C:/Notebook/data1.txt','r') as csvinput:
    with open('C:/Notebook/datawr1.txt', 'w') as csvoutput:
        writer = csv.writer(csvoutput, lineterminator='\n')
        reader = csv.reader(csvinput)

        all = []
        row = next(reader)
        row.append('Timing') # Here I create a column "Timing"
        all.append(row)

        for row in reader:  #I think here should be a condition if
            row.append(' ') 
            all.append(row)           


        writer.writerows(all)

【问题讨论】:

    标签: python csv pandas ipython-notebook


    【解决方案1】:

    我认为您可以通过字典d 使用map,如果不匹配则获取NaN:

    df = pd.DataFrame({'type':['dgv','ds','psp', 'a']})
    print (df)
      type
    0  dgv
    1   ds
    2  psp
    3    a
    
    d = {'dgv':17,'ds':8,'psp':3}
    df['Timing'] = df['type'].map(d)
    print (df)
      type  Timing
    0  dgv    17.0
    1   ds     8.0
    2  psp     3.0
    3    a     NaN
    

    编辑:

    在pandas中读取文件使用read_csv,写入to_csv(如果是.txt文件没问题):

    import pandas as pd
    from pandas.compat import StringIO
    
    temp=u"""code,type,date,quantity
    0,dgv,07.11.2016,1
    0,dgv,08.06.2016,1
    0,ds,01.07.2016,1
    0,ds,03.08.2016,1
    0,ds,03.08.2016,1
    0,psp,06.03.2016,1
    0,a,07.08.2016,1"""
    #after testing replace 'StringIO(temp)' to 'filename.txt'
    df = pd.read_csv(StringIO(temp))
    print (df)
       code type        date  quantity
    0     0  dgv  07.11.2016         1
    1     0  dgv  08.06.2016         1
    2     0   ds  01.07.2016         1
    3     0   ds  03.08.2016         1
    4     0   ds  03.08.2016         1
    5     0  psp  06.03.2016         1
    6     0    a  07.08.2016         1
    

    d = {'dgv':17,'ds':8,'psp':3}
    df['Timing'] = df['type'].map(d)
    print (df)
       code type        date  quantity  Timing
    0     0  dgv  07.11.2016         1    17.0
    1     0  dgv  08.06.2016         1    17.0
    2     0   ds  01.07.2016         1     8.0
    3     0   ds  03.08.2016         1     8.0
    4     0   ds  03.08.2016         1     8.0
    5     0  psp  06.03.2016         1     3.0
    6     0    a  07.08.2016         1     NaN
    
    df.to_csv('myfile.txt', index=False)
    

    【讨论】:

    • 感谢您的回答!但问题是文件中有很多数据。该文件为 .txt 格式。而且文件每次都不一样。我希望代码读取文件并添加“Timing”列并填充它。我不明白如何将列“类型”称为日期框架。
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2019-01-21
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多