I am very new to programming so please be patient with me.
I am reading from a .csv like so:
1, -2
2, 3
3, -6
4, 5
5, 7
and so on. My goal here, essentially is just to delete the first row, and then decrement the remaining first column by 1, so I'd have something like..
1, 3
2, -6
3, 5
4, 7
5, *some randomly generated number*
Here is what I have so far:
del data[0]
for i in range(len(data)):
newTime = data[i][0] - 1
oldNum = data[0][1]
data.insert(i, [newTime, oldNum])
however this is just taking 1, 3 and inserting it len(data) times.. what am I doing wrong? Please don't be mean, I really am trying to learn!
I was using this as guidance: http://docs.python.org/release/1.5.1p1/tut/range.html, and to me it seems like this should work.. :/ Haaaalp!
import random
data = [[1,2],
[2,4],
[3,-5],
[4,9],
[5,7]]
l = len(data)
for i in range(l-1):
data[i][1] = data[i+1][1]
data[l-1][1] = random.randint(-3,3)
print(data)
output:
[[1, 4],
[2, -5],
[3, 9],
[4, 7],
[5, 0]]
Commenting on the posted code, I don't understand why it would use a csv library to read all the lines out of a file and then split the lines with lower level methods. Doing too much will cause bugs, even for experts. Let the library or framework do as much as it can for you and make your own code reasonably short.
A modern library for data is pandas, which includes support for reading various data file formats including CSV.
Here's how one could read in a csvfile with a column "name", subset the file data name>=2, deduct one from name, and write it back out.
Tested as shown below
import pandas as pd
import random
DIN = pd.read_csv("csvfile.csv")
DOUT = DIN[DIN['name']>=2]
DOUT['name']=DOUT['name']-1
DOUT = pd.concat([DOUT, pd.DataFrame({'name': DOUT['name'].tail(1)+1, 'value': int(random.random()*100)})])
DOUT.to_csv("newcsvfile.csv", index=False)
in
"name","value"
1,1
2,2
3,3
4,4
5,5
6,4
7,3
8,2
9,1
out
name,value
1,2
2,3
3,4
4,5
5,4
6,3
7,2
8,1
9,76
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With