我有一张桌子。我正在创建一个新专栏“Timing”。我需要用数字填充它,具体取决于“类型”列中的数据。例如,如果在列“type”的单元格中是dgv,那么在“timing”列中应该有一个数字17,如果是ds,则为8,如果是psp,则为3,等等。总共有几个条件
我的代码:
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)
答案 0 :(得分:1)
我认为您可以使用d
字典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
:
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
编辑:
在用于阅读文件的pandas中使用map
来编写read_csv
(如果是.txt文件则没问题):
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)
C:\Users\UserName\AppData\Roaming\NuGet