Use-case description: Have a csv file which has two rows and five columns. The csv file contains the data of the user where owner column has just first name, followed by language which includes last name, email column with language(English) and empty header with value email id. Key highlighter of the use case is - the column owner should contain the first name & the last name, rest goes as per the below screenshot given from the csv file. End Result expected: Need to to shift the values of row #2 each by (-1)cell which should be aligned with the header values of the CSV file. Trying the same using the Python code But NO luck. Finding still deeper to dive into it & any guidance on this will be highly appreciated!!
-
Have you tried coding something ? Where are you at ? this shoudn't be hard to be done with pandas.coyote– coyote2021-09-07 09:21:32 +00:00Commented Sep 7, 2021 at 9:21
-
@coyote ,yes tried couple of codes with pandas. Sharing a latest code snip: df = pd.read_csv('abcd.csv') df.shift(-1, axis = 1). Error message: File "pandas/_libs/parsers.pyx", line 545, in pandas._libs.parsers.TextReader.__cinit__ EmptyDataError: No columns to parse from file Looking forward to crack the code!Anirudh Bragadeesan– Anirudh Bragadeesan2021-09-07 10:29:49 +00:00Commented Sep 7, 2021 at 10:29
Add a comment
|
1 Answer
This will shift the second row to the left in a CSV file with python, you can change it to shift other rows too
import csv
with open("yourfile.csv") as csv_file:
csv_reader = csv.reader(csv_file)
with open("newfile.csv", "w", newline='') as new_csv_file:
csv_writer = csv.writer(new_csv_file)
i = 0
for row in csv_reader:
if i == 1:
row.pop(0)
csv_writer.writerow(row)
i += 1
3 Comments
Anirudh Bragadeesan
thanks for the response. tried the above code but unfortunately it is not executing the code instead of that it is just displaying the following on the output console: "runfile('D:/Hosting/Code/Script/script.py', wdir='D:/ Hosting/Code/Script')" .i am actually looking for a code which could help in shifting the values of second row to the left & NOT removing the rows.Great if you can tweak on the same.
purp1e
Ah sorry I made a mistake in my writing, this doesn't remove the second row, it shifts it one to the left. I'll edit it now.
Anirudh Bragadeesan
Hey @purp1e thank you for a lot...seems we can test the same code and take it further...Great that you helped with code for the same...:)
