-1

我正在尝试从以字符串形式显示的日期列表中在 Pandas 中创建一个系列,因此:

['2016-08-09',
 '2015-08-03',
 '2017-08-15',
 '2017-12-14',
...

但是当我从 Pandas 模块中应用 pd.Series 时,Jupyter 笔记本中的结果显示为:

0       [[[2016-08-09]]]
1       [[[2015-08-03]]]
2       [[[2017-08-15]]]
3       [[[2017-12-14]]]
...

有没有简单的方法来解决它?数据来自使用 lxml.objectify 解析的 Xml 提要。

从 csv 读取时,我通常不会遇到这些问题,只是好奇我可能做错了什么。

更新:

获取数据的代码和示例站点:

导入 lxml.objectify 将 pandas 导入为 pd

def parse_sitemap(url):
        root = lxml.objectify.parse(url)
        rooted = root.getroot()
        output_1 = [child.getchildren()[0] for child in rooted.getchildren()]
        output_0 = [child.getchildren()[1] for child in rooted.getchildren()]
        return output_1

results = parse_sitemap("sitemap.xml")
pd.Series(results)
4

2 回答 2

2

如果你打印出来type(result[0]),你就会明白,这不是你得到的字符串:

print(type(results[0]))

输出:

lxml.objectify.StringElement

这不是一个字符串,pandas 似乎不太喜欢它。但修复很容易。只需使用以下命令转换为字符串pd.Series.astype

s = pd.Series(results).astype(str)
print(s)

0     2017-08-09T11:20:38Z
1     2017-08-09T11:10:55Z
2     2017-08-09T15:36:20Z
3     2017-08-09T16:36:59Z
4     2017-08-02T09:56:50Z
5     2017-08-02T19:33:31Z
6     2017-08-03T07:32:24Z
7     2017-08-03T07:35:35Z
8     2017-08-03T07:54:12Z
9     2017-07-31T16:38:34Z
10    2017-07-31T15:42:24Z
11    2017-07-31T15:44:56Z
12    2017-07-31T15:23:25Z
13    2017-08-01T08:30:27Z
14    2017-08-01T11:01:57Z
15    2017-08-03T13:52:39Z
16    2017-08-03T14:29:55Z
17    2017-08-03T13:39:24Z
18    2017-08-03T13:39:00Z
19    2017-08-03T15:30:58Z
20    2017-08-06T11:29:24Z
21    2017-08-03T10:19:43Z
22    2017-08-14T18:42:49Z
23    2017-08-15T15:42:04Z
24    2017-08-17T08:58:19Z
25    2017-08-18T13:37:52Z
26    2017-08-18T13:38:14Z
27    2017-08-18T13:45:42Z
28    2017-08-03T09:56:42Z
29    2017-08-01T11:01:22Z
dtype: object
于 2017-08-26T16:45:47.343 回答
0

我认为你需要做的就是:

pd.Series(dates)

但问题中没有足够的信息可以肯定地说。

另外,如果你想使用datetime64对象,你可以这样做:

pd.Series(pd.to_datetime(dates))
于 2017-08-26T16:37:36.180 回答