简体   繁体   English

将CSV文件读取到pandas DataFrame中,并从多个列中构建日期时间索引

[英]read CSV file into pandas DataFrame, and build datetime index from multiple columns

I have a CSV file like this: 我有这样的CSV文件:

2011    1   10  1000000
2011    1   11  998785
2011    1   12  1002940
2011    1   13  1004815
2011    1   14  1009415
2011    1   18  1011935

I want to read it into a DataFrame object and have a datetime typed index built from the frist 3 colomns. 我想将其读入DataFrame对象,并具有从第3个列构建的datetime类型的索引。 The final DataFrame should look like this: 最终的DataFrame应该如下所示:

                     values
datetime(2011,1,10)  1000000
datetime(2011,1,11)  998785
...

How should I do that? 我应该怎么做? Thanks a lot! 非常感谢!

import io
import pandas as pd
content = io.BytesIO('''\
2011    1   10  1000000
2011    1   11  998785
2011    1   12  1002940
2011    1   13  1004815
2011    1   14  1009415
2011    1   18  1011935''')

df = pd.read_table(content, sep='\s+', parse_dates=[[0,1,2]], header=None)
df.columns=['date', 'values']
print(df)

yields 产量

                 date   values
0 2011-01-10 00:00:00  1000000
1 2011-01-11 00:00:00   998785
2 2011-01-12 00:00:00  1002940
3 2011-01-13 00:00:00  1004815
4 2011-01-14 00:00:00  1009415
5 2011-01-18 00:00:00  1011935

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将csv文件读取到具有多行索引级别的pandas DataFrame中? - How to read csv file into pandas DataFrame with multiple row index level? 如何将数据从 csv 读取到具有多列的 pandas dataframe 中? - How can the data be read from a csv into a pandas dataframe, with multiple columns? Pandas 从剪贴板读取带有日期时间列的 DataFrame - Pandas read DataFrame with datetime columns from clipboard 如何让 pandas.read_csv() 从 CSV 文件列推断日期时间和时间增量类型? - How to get pandas.read_csv() to infer datetime and timedelta types from CSV file columns? pandas dataframe:seaborn Z32FA6E1B78A9D4028953E605Z4A2作为索引的多列日期时间栏 - pandas dataframe : seaborn plot bar with multiple columns and datetime as index Pandas:如何从没有索引的 csv 文件中读取多索引列 dataframe? - Pandas: how to read a multi-index column dataframe from a csv file without an index? 将多个 csv 文件读入单个数据帧并根据原始文件重命名列 - Pandas - Read multiple csv files into a single dataframe and rename columns based on file of origin - Pandas Pandas从csv读取数据帧,索引为字符串,而不是int - Pandas read dataframe from csv with index as string, not int Pandas 将 csv dateint 列读取到 datetime - Pandas read csv dateint columns to datetime Python Pandas-read_csv数据框正在从列中删除值 - Python pandas - read_csv Dataframe is dropping values from columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM