2020-09-08
阅读量:
1318
pandas操作excel中各列内容:合并、拆列、去重、日期格式转换等
import pandas as pd df=pd.read_excel(r'D:\CDA\CDA_PGC\datas.xlsx',sheetname='Sheet1') df['日期']=df['日期'].dt.date #去掉‘时分秒’(从excel导入的日期数据默认00:00:00) df['合并列']=df['编号'].map(str)+','+df['日期'].map(str) #将pandas默认的pandas默认的int64类型转为字符串 df
Out[15]:
| 编号 | 日期 | 合并列 | |
|---|---|---|---|
| 0 | 123 | 2020-09-09 | 123,2020-09-09 |
| 1 | 123 | 2020-09-08 | 123,2020-09-08 |
| 2 | 345 | 2020-09-09 | 345,2020-09-09 |
| 3 | 345 | 2020-09-08 | 345,2020-09-08 |
| 4 | 345 | 2020-09-09 | 345,2020-09-09 |
| 5 | 123 | 2020-09-09 | 123,2020-09-09 |
In [16]:
df.drop_duplicates('合并列',inplace=True)
dfOut[16]:
| 编号 | 日期 | 合并列 | |
|---|---|---|---|
| 0 | 123 | 2020-09-09 | 123,2020-09-09 |
| 1 | 123 | 2020-09-08 | 123,2020-09-08 |
| 2 | 345 | 2020-09-09 | 345,2020-09-09 |
| 3 | 345 | 2020-09-08 | 345,2020-09-08 |
In [17]:
df.drop(labels=['编号','日期'],axis=1,inplace=True) df
Out[17]:
| 合并列 | |
|---|---|
| 0 | 123,2020-09-09 |
| 1 | 123,2020-09-08 |
| 2 | 345,2020-09-09 |
| 3 | 345,2020-09-08 |
In [18]:
df['编号'],df['日期']=df['合并列'].str.split(',',1).str
dfOut[18]:
| 合并列 | 编号 | 日期 | |
|---|---|---|---|
| 0 | 123,2020-09-09 | 123 | 2020-09-09 |
| 1 | 123,2020-09-08 | 123 | 2020-09-08 |
| 2 | 345,2020-09-09 | 345 | 2020-09-09 |
| 3 | 345,2020-09-08 | 345 | 2020-09-08 |
In [19]:
df=df.drop(labels=['合并列'],axis=1) df
Out[19]:
| 编号 | 日期 | |
|---|---|---|
| 0 | 123 | 2020-09-09 |
| 1 | 123 | 2020-09-08 |
| 2 | 345 | 2020-09-09 |
| 3 | 345 | 2020-09-08 |
In [20]:
df.to_excel(r'D:\CDA\CDA_PGC\datas2.xlsx',index=None)#删除index列
77.5233
3
0
关注作者
收藏
评论(0)
发表评论
暂无数据

