【发布时间】:2021-04-29 09:52:14
【问题描述】:
我已经连接了两个数据框,连接前的列类型是日期时间,但连接后的列类型变成了对象,当我导出到excel时它完全改变了!
这是两个数据框:
df_last_month:
| project number | status | Project Naming | CF | VPC | CO | MA |
|---|---|---|---|---|---|---|
| A | Planned | DH | 2021-01-26 | 2021-03-16 | 2021-11-16 | 2023-10-10 |
| B | frozen | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
| C | Planned | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
| D | Planned | HH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
df_current_month:
| project number | status | Project Naming | CF | VPC | CO | MA |
|---|---|---|---|---|---|---|
| A | Planned | DH | 2021-01-10 | 2021-03-16 | 2021-09-16 | 2023-10-10 |
| B | frozen | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
| E | completed | DH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
| F | completed | HH | 2017-12-01 | 2018-12-18 | 2019-07-26 | 2022-02-18 |
| H | completed | HH | 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')
这是输入:
我想要做的是:在列中(CF、CO、MA、VPC)我有两种格式:
- 第一个:[2021-01-26 00:00:00]
- 第二次:[2021-01-26 00:00:00,2021-01-10 00:00:00]
-
我想删除时间。
-
然后当我导出到 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)
有什么建议吗?感谢您的帮助
【问题讨论】:
-
你能提供一些文本格式的数据而不是图像吗?
-
您的日期时间列似乎是一个列表[datetime1, datetime2]
-
您的问题是您正在创建一个充满数组的数据框——您是如何得到它的?可以分享一下代码吗?
-
@Epsi95 我添加了我使用的数据
-
@Manakin 我添加第一个代码和数据
标签: python excel pandas date object