![](/img/trans.png)
[英]How to extract data from rows in .csv file into separate .txt files using python?
[英]How to extract last 1year and 6months data from a .txt into two separate .txt files delimited by '\t'?
你可以试试:
df = pd.read_csv('data.txt', sep='\t', parse_dates=True) #load
df.date = pd.to_datetime(df.date, infer_datetime_format=True) #convert to date if needed
first = df[df['date'].dt.year == 2020] #subset; note you might use other criteria here
second = df[df['date'].dt.year < 2020]
编辑
根据您的评论,这里是模拟数据,以便您可以测试代码:
df = pd.DataFrame({
'date': ['05-10-2020', '06-07-2020', '06-12-2019'],
'test' : ['one', 'two', 'three'],
'thingy': ['re', 'rho', 'rha']
})
df
请注意,您的原始数据仍在df
中。
您还可以将日期定义为索引,然后是子集:
df.set_index('date', inplace=True) #set index
子集并保存:
first = df.loc['2020-01-01':'2020-06-30'] #specify date range
second = df.loc['2020-07-01':'2020-12-31']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.