![](/img/trans.png)
[英]Read first column in csv every time and change other columns in python
[英]I have a csv file name timestamp.csv,in which first column is of Time.I need to change the format of time in each column
csv 中的時間格式類似於 2022-05-12 10:38:21 594.666 但我需要將其更改為 2022-05-12 10:38:21.594666。 我需要將所有值替換為這個表達式 %Y-%m-%d %H:%M:%S %f 我被困在這里
import pandas as pd
a = pd.read_csv("timestamp.csv")
df=pd.DataFrame(a,columns=['Time'])
df=df.replace([','],'')
這段代碼不會改變我的格式。
我希望這種 10:38:21 594.666 格式在所有時間行中都變為 10:38:21.594666
一種方法是將其分成兩個易於處理的部分,然后將它們重新組合在一起:
鑒於:
timestamp
0 2022-05-12 10:38:21 594.666
正在做:
# Split into two cols:
df[['timestamp', 'ms']] = df.timestamp.str.split(' (?=\S+$)', expand=True)
# Process the timestamp:
df.timestamp = pd.to_datetime(df.timestamp)
# Process the Milliseconds:
df.ms = pd.to_timedelta(df.ms.astype(float), unit='ms')
# Combine them again:
df.timestamp = df['timestamp'] + df['ms']
# Drop our helper column:
df = df.drop('ms', axis=1)
print(df)
Output:
timestamp
0 2022-05-12 10:38:21.594666
鑒於時間列不是官方時間格式,我將其全部視為字符串,然后使用字符串替換。 它不漂亮,但它有效。
import pandas as pd
# input filename
filename = "testdata.txt"
# explicitly force column datatypes to string
col_types = {
"Time": str,
"othercolumn1": str,
"othercolumn2": str,
"etc": str
}
# read csv file
df = pd.read_csv(filename, sep=',', dtype=col_types)
# it ain't pretty but it works
df['Time'] = df['Time'].str.replace('.', '', regex=False)
df['Time'] = df['Time'].str.replace(' ', '.', regex=False) # replace ALL spaces
df['Time'] = df['Time'].str.replace('.', ' ', 1, regex=False) # replace FIRST dot only
# csv write new output
df.to_csv("output.txt", sep=',', header=True, index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.