我遇到了一个问题,我只需要更改我的dataframe头的部分列的数据类型。
我的标题如下所示:
‘名称’经理‘评审经理’3-2月3日-20日‘10’-2月20日‘’17‘2月17日-20日’24‘-2月20日’2‘2-3月-20’9-3月20‘16-3月20’23‘23-3月-20’30-3月20日-20日
我只想更改作为日期出现的标题值的数据类型:“3-2月-20‘10-2月10-20’17-2月20‘24’-2月-20‘2-3月-20’16-3月-20‘23-3月-20’30‘-3月-20’30‘-20’
我不想只将1-3列的标题从第4列更改为最后一列.
我所尝试的如下:
df2 = pd.read_excel(r'C:\Tracker.xlsx', skiprows=range(1,6), sheet_name='Status', header=[1])我知道我可以将列的数据类型更改为:
df.column_name = df.column_name.astype(datatype) wb = openpyxl.load_workbook(r'C:\Tracker.xlsx')
ws = wb.active
column = ws.max_column
row = ws.max_row发布于 2020-03-18 12:45:19
若要使用df.columns.astype(newtype)更改列名日期类型,请执行以下操作。见下面的例子。
在此excel文件中,前2个列名是字符串,接下来的4个列名是日期值。
df = pd.read_excel('text.xlsx')
print([(col, type(col)) for col in df.columns])输出:
[('col0', <class 'str'>), ('col1', <class 'str'>), (datetime.datetime(2017, 7, 9, 0, 0), <class 'datetime.datetime'>), (datetime.datetime(2017, 7, 10, 0, 0), <class 'datetime.datetime'>), (datetime.datetime(2017, 7, 11, 0, 0), <class 'datetime.datetime'>), (datetime.datetime(2017, 7, 13, 0, 0), <class 'datetime.datetime'>)]将列名的数据类型转换为str
df.columns = df.columns.astype(str)
print([(col, type(col)) for col in df.columns])输出:
[('col0', <class 'str'>), ('col1', <class 'str'>), ('2017-07-09 00:00:00', <class 'str'>), ('2017-07-10 00:00:00', <class 'str'>), ('2017-07-11 00:00:00', <class 'str'>), ('2017-07-13 00:00:00', <class 'str'>)]您可以看到,所有列名、数据类型现在都是str。
https://stackoverflow.com/questions/60738580
复制相似问题