0

I am trying to write a simple program to edit existing numbers in a text file using the pandas library.

I have a text file with the following format:

"===================================================================================================================================="

    ----- whole bunch of text here ----- 

"===================================================================================================================================="
 "variable1","Variable2","Variable3"
 "unit1","unit2","unit3"
 ------,------,------
 1,0.800,12161.31
 2,0.883,1623669.24

    ------ some other stuff here ----------

I am interested in only the two numbers under variable3/unit3 : 12161.31 and 1623669.24

I would like to be able to add/subtract numbers from these values.

Currently, I can seperate the values of interest from the txt file by a pd.read_csv method:

data = pd.read_csv(str(infilename), sep ='/t', header = None, skiprows = 2, index_col = None)

new_data = data[24:26]
print(new_data)

out:

24  1,0.800,12161.31
25  2,0.883,1623669.24

However, I cannot think of a way to replace the original values with the newly edited ones. Is this possible using the pandas library?

Joey
  • 914
  • 4
  • 16
  • 37
  • check this out ->https://stackoverflow.com/a/31247247/9754169 – Yuca Dec 03 '18 at 16:04
  • I am not trying to append the data, i'm trying to edit the numbers in the existing file without changing any of its existing structure. – Joey Dec 03 '18 at 16:06
  • 2
    you load them into a dataframe, you edit the dataframe, and then use the `to_csv` to update the file. How much you modify the original contents depends on the structure of your original file. Pandas may not be the correct library for your task – Yuca Dec 03 '18 at 16:08
  • By this method, the final csv file will only contain the edited numbers and nothing else from the original file. – Joey Dec 03 '18 at 16:12
  • you could change data.iloc[24:26,2] = [new_value1, new_value2] and then store using `data.to_csv`. That's what I said on my previous comments but it doesn't hurt to be more explicit :) – Yuca Dec 03 '18 at 16:14
  • I tried but I'm getting an index error with this for some reason. IndexError: single positional indexer is out-of-bounds – Joey Dec 03 '18 at 16:22
  • without the actual data is really cumbersome. You have the roadmap to do it. The index error is easy to fix, look at the shape of data and check that there are indeed 26 rows and 3 columns – Yuca Dec 03 '18 at 16:24

0 Answers0