我已经串联了两个数据帧,串联之前的列类型是日期时间,但是串联之后,列类型更改为对象,而当我导出为excel时,列类型完全改变了!
这是两个数据框:
df_last_month:
项目编号 | 状态 | 项目命名 | 碳纤维 | VPC | 一氧化碳 | 嘛 |
---|---|---|---|---|---|---|
一种 | 计划 | DH | 2021-01-26 | 2021-03-16 | 2021-11-16 | 2023-10-10 |
乙 | 冷冻的 | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
C | 计划 | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
d | 计划 | H | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
df_current_month:
项目编号 | 状态 | 项目命名 | 碳纤维 | VPC | 一氧化碳 | 嘛 |
---|---|---|---|---|---|---|
一种 | 计划 | DH | 2021-01-10 | 2021-03-16 | 2021-09-16 | 2023-10-10 |
乙 | 冷冻的 | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
Ë | 已完成 | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
F | 已完成 | H | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
H | 已完成 | H | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
我已经将df1和df2与某些条件串联在一起,这是代码:
df_last_month = df_last_month.set_index('project number')
df_current_month = df_current_month.set_index('project number')
df3 = pd.concat([df_last_month,df_current_month],sort=False)
df3a = df3.stack().groupby(level=[0,1]).unique().unstack(1).copy()
df3a.loc[~df3a.index.isin(df_last_month.index),'update_project'] = 'new'
df3a.loc[~df3a.index.isin(df_current_month.index),'update_project'] ='deleted'
idx = df3.stack().groupby(level=[0,1]).nunique()
df3a.loc[idx.mask(idx<=1).dropna().index.get_level_values(0),
'update_project'='modified'
df3a['update_project'] = df3a['update_project'].fillna('same')
这是输入:
我想做的是:在column(CF,CO,MA,VPC)中,我有两种格式:
我想删除时间。
然后当我导出到excel时,我也将使用相同的格式,我的意思是[2021-01-26]或[2021-01-26,2021-01-10],但是现在我在excel中有了它:
这是我的代码:
import pandas as pd
import numpy as np
from datetime import datetime, date
# Classify date column by format type
df['format'] = 1
df.loc[df['CF'].astype(str).str.contains(','), 'format'] = 2
df['new_date'] = pd.to_datetime(df['CF'])
# Convert to datetime with two different format settings
df.loc[df.format == 1, 'new_date'] = pd.to_datetime(df.loc[df.format == 1, 'CF'], format = '%Y-%d-%m %H:%M:%S').dt.strftime('%Y-%m-%d')
df.loc[df.format == 2, 'new_date'] = pd.to_datetime(df.loc[df.format == 2, 'CF'], format = '%m/%d/%Y %H:%M:%S,%m/%d/%Y %H:%M:%S').dt.strftime('%Y-%m-%d,%m/%d/%Y')
print(df)
有什么建议 ?谢谢你的帮助
在连接两个数据框之前如何将Datetime列转换为字符串。这样,您就可以获得所需的输出。
from pandas.api.types import is_datetime64_any_dtype
for col in df_current_month.columns:
if is_datetime64_any_dtype(df_current_month[col]):
df_current_month[col] = df_current_month[col].dt.strftime('%Y-%m-%d')
df_current_month['CF'].head()
0 2021-10-01
1 2017-01-12
2 2017-01-12
3 2017-01-12
4 2017-01-12
Name: CF, dtype: object
不幸的是,您必须对两个数据框都执行此操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句