有一个如下所示的 XML 文件:
?<?xml version="1.0" encoding="utf-8"?>
<comments>
<row Id="1" PostId="2" Score="0" Text="(...)" CreationDate="2011-08-30T21:15:28.063" UserId="16" />
<row Id="2" PostId="17" Score="1" Text="(...)" CreationDate="2011-08-30T21:24:56.573" UserId="27" />
<row Id="3" PostId="26" Score="0" Text="(...)" UserId="9" />
</comments>
Run Code Online (Sandbox Code Playgroud)
我想要做的是将 ID、Text 和 CreationDate 列提取到 Pandas DF 中,我尝试了以下操作:
import xml.etree.cElementTree as et
import pandas as pd
path = '/.../...'
dfcols = ['ID', 'Text', 'CreationDate']
df_xml = pd.DataFrame(columns=dfcols)
root = et.parse(path)
rows = root.findall('.//row')
for row in rows:
ID = row.find('Id')
text = row.find('Text')
date = row.find('CreationDate')
print(ID, text, date) …Run Code Online (Sandbox Code Playgroud) 我有一个Pandas数据帧,我需要将日期的列转换为int,但不幸的是,所有给定的解决方案都会出现错误(如下)
test_df.info()
<class 'pandas.core.frame.DataFrame'>
Data columns (total 4 columns):
Date 1505 non-null object
Avg 1505 non-null float64
TotalVol 1505 non-null float64
Ranked 1505 non-null int32
dtypes: float64(2), int32(1), object(1)
Run Code Online (Sandbox Code Playgroud)
样本数据:
Date Avg TotalVol Ranked
0 2014-03-29 4400.000000 0.011364 1
1 2014-03-30 1495.785714 4.309310 1
2 2014-03-31 1595.666667 0.298571 1
3 2014-04-01 1523.166667 0.270000 1
4 2014-04-02 1511.428571 0.523792 1
Run Code Online (Sandbox Code Playgroud)
我想我已经尝试了一切,但没有任何作用
test_df['Date'].astype(int):
Run Code Online (Sandbox Code Playgroud)
TypeError:int()参数必须是字符串,类字节对象或数字,而不是'datetime.date'
test_df['Date']=pd.to_numeric(test_df['Date']):
Run Code Online (Sandbox Code Playgroud)
TypeError:位置0处的对象类型无效
test_df['Date'].astype(str).astype(int):
Run Code Online (Sandbox Code Playgroud)
ValueError:基数为10的int()的无效文字:'2014-03-29'
test_df['Date'].apply(pd.to_numeric, errors='coerce'):
Run Code Online (Sandbox Code Playgroud)
将整个列转换为NaN