Pandas模块 --- 字符与日期型数据的处理


 

1,pd.to_datetime( 要转换的日期, format= ),

2,pd.to_datetime.today( ).year  ,pd.to_datetime.now( ).year

3,字符串的astype方法:字段类型转换,

4,日期.dt.year  :必须加dt

5,删除字段: df. drop ([ ] , axis=1, inplace=True)

    df是数据框的名字,列表[  ] 里是要删除的字段名,

    axis=1表示在水平方向,因为默认drop方法是用来删除数据库中的行记录,

    inplace=True表示会影响原数组

 6,序列的apply ( )  方法  ,  apply( func= , )

 7,序列使用.str后,可以转换为字符串类型

 

 

df=pd.read_excel(r'E:\Python学习资料\data_test03.xlsx')
# print(df)
print("df的类型:",type(df))
print("数据集DataFrame的维数:",df.ndim)
print("元素类型:\n",df.dtypes)
print("\n元素个数:",df.size)

#转换字段的数据类型
df.birthday=pd.to_datetime(df.birthday,format='%Y-%m-%d')
df.tel=df.tel.astype("str")

#将手机号中间4位隐藏起来
df.tel=df.tel.apply(func=lambda x:x.replace(x[3:7],"*****"))

#添加域名domain,年龄age,工龄workage,专业profession
df['domain']=df.email.apply(func=lambda x:x.split("@")[1])
df['age']=pd.datetime.today().year-df.birthday.dt.year
df['workage']=pd.datetime.today().year-df.birthday.dt.year
df['profession']=df.other.str.findall("专业:(.*?),")
#这种方法能去掉专业外面的 中括号
df['major']=df.other.str.findall("专业:(.*?),").str[0]

#删除'birthday','start_work','other'这几个变量
df.drop(['birthday','start_work','other'],axis=1,inplace=True)

#各种操作之后的数据集
print("\n",df)

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM