简体   繁体   English

在pandas中使用to_dict()时,无法将列标题附加到数据框

[英]Can't append column headers to dataframe when using to_dict() in pandas

I have a key/value paired dict of (datetime/object) variables and am having trouble appending a header and dtypes to the data types. 我有(datetime / object)变量的键/值配对字典,并且无法在数据类型中附加标题和dtypes。

I can make a dataframe with no column headers and dtype of object which is what I don't want. 我可以创建一个没有列标题的数据框和对象的dtype,这是我不想要的。 I'm trying to use the dtype and column parameters but am only being met with errors. 我正在尝试使用dtype和column参数,但我只遇到错误。

My code to create my dict: 我创建我的dict的代码:

for files_local in glob.glob(share_dr + '/**/*.csv', recursive=True):
    match = re.search(get_matches_regex, files_local)
    if match and match.group(0):
        d = datetime.datetime.strptime  # short form
        dict_of_files_local[d(match.group('fileDate'), '%Y%m%d_%H%M%S')] = files_local

My dict when looping through: 循环时我的字典:

2019-02-07 09:11:39 C:\csv\myfile_20190207_091139_092739.csv
2019-02-08 03:08:11 C:\csv\myfile_20190208_030811_031734.csv

This all works, great, but when I try to add it to a dataframe using: 这一切都很有用,但当我尝试使用以下方法将其添加到数据框时:

df = pd.DataFrame.from_dict(dict_of_files_local, orient='index', dtype=['datetime', 'object'], columns=['Timestamp', 'Filename'])

I'm getting the error: 我收到错误:

TypeError: data type not understood

Why is this? 为什么是这样? I thought pandas was had great datetime parsing availability? 我以为熊猫有很好的日期时间解析可用性?

How can I solve this problem? 我怎么解决这个问题? Am still rather new to python/pandas BTW. 对于python / pandas BTW来说还是比较新的。

Thanks a lot ! 非常感谢 !

I have managed to find a workaround, which is just by passing the dict.items() to the pd.DataFrame parameter. 我已经设法找到一个解决方法,只需将dict.items()传递给pd.DataFrame参数即可。

My code below: 我的代码如下:

df = pd.DataFrame(dict_of_files_local.items(), columns=['Timestamp', 'Filename'])

Now outputs the following: 现在输出以下内容:

            Timestamp                           Filename
0 2019-02-07 09:11:39  C:\csv\myfile_20190207_091139_...
1 2019-02-08 03:08:11  C:\csv\myfile_20190208_030811_...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM