Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

Python: pandas.DataFrame.to_csv is not populating the output column

I have the following code that is basically changing the format of a UTC timestamp from mm/dd/yyyy hh:mm:ss AM to dd/mm/yyyy hh:mm:ss AM. It is working fine but now I need it to either replace the old column in the same csv file or create another csv file but with the modified date format. The thing is that when I run the code the UTC timestamp column is empty, it has the header though.

Here is the code

import pandas as pd
import datetime
from datetime import datetime
from datetime import time

df = pd.read_csv("C:/Users/javie/OneDrive/Escritorio/22.1.21_P1_English_Language_Y10.csv")

df[' UTC Event Timestamp'] = pd.to_datetime(df[' UTC Event Timestamp'])
df[' UTC Event Timestamp'] = df[' UTC Event Timestamp'].apply(lambda x: print(x.strftime('%d/%m/%Y %I:%M:%S %p')))

df.to_csv("C:/Users/javie/OneDrive/Escritorio/output.csv",index=False,date_format='%d/%m/%Y %I:%M:%S %p')
question from:https://stackoverflow.com/questions/65891782/python-pandas-dataframe-to-csv-is-not-populating-the-output-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is almost there. The usage of print() is not necessary, that is where your problem comes from.

Remove that and your code should work:

import pandas as pd
import datetime
from datetime import datetime
from datetime import time

df = pd.read_csv("C:/Users/javie/OneDrive/Escritorio/22.1.21_P1_English_Language_Y10.csv")

df[' UTC Event Timestamp'] = pd.to_datetime(df[' UTC Event Timestamp'])
df[' UTC Event Timestamp'] = df[' UTC Event Timestamp'].apply(lambda x: x.strftime('%d/%m/%Y %I:%M:%S %p'))

df.to_csv("C:/Users/javie/OneDrive/Escritorio/output.csv",index=False,date_format='%d/%m/%Y %I:%M:%S %p')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...