经常会有一些朋友问我类似的问题,“哎呀,这个数据该怎么处理啊,我希望结果是这样的,麻烦刘老师帮我看看。
”、“刘老师,怎么把一列数据拆分出来,并取出最后一个拆分结果呀?
”、“刘老师,怎么将 Json 数据读入到 Python 中呢?
”。
在我看来,这些问题都可以借助于 Pandas 模块完成,因为 Pandas 属于专门做数据预处理的数据科学包。
下面来介绍一下我认为 Pandas 模块中需要掌握的功能和函数。
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='test',
database='test', port=3306, charset='utf8')
user = pd.read_sql('select * from topy', conn)
conn.close()
User
sec_cars = pd.read_table(r'C:\Users\Administrator\Desktop\sec_cars.csv', sep = ',')
sec_cars.head()
print('数据集的行列数:\n',sec_cars.shape)
print('各变量的数据类型:\n',sec_cars.dtypes)
sec_cars.describe()
df = pd.read_excel(r'C:\Users\Administrator\Desktop\data_test05.xlsx')
print('数据集中是否存在缺失值:\n',any(df.isnull()))
df.dropna()
df.drop('age', axis = 1)
df.fillna(method = 'ffill')
df.fillna(method = 'bfill')
df.fillna(value = 0)
df.fillna(value = {'gender':df.gender.mode()[0], 'age':df.age.mean(),
'income':df.income.median()})
df = pd.read_excel(r'C:\Users\Administrator\Desktop\data_test03.xlsx')
df.birthday = pd.to_datetime(df.birthday, format = '%Y/%m/%d')
df.tel = df.tel.astype('str')
df['age'] = pd.datetime.today().year - df.birthday.dt.year
df['workage'] = pd.datetime.today().year - df.start_work.dt.year
df.tel = df.tel.apply(func = lambda x : x.replace(x[3:7], '****'))
df['email_domain'] = df.email.apply(func = lambda x : x.split('@')[1])
df['profession'] = df.other.str.findall('专业:(.*?),')
df.drop(['birthday','start_work','other'], axis = 1, inplace = True)
df1 = pd.DataFrame({'name':['张三','李四','王二'], 'age':[21,25,22],
'gender':['男','女','男']})
df2 = pd.DataFrame({'name':['丁一','赵五'], 'age':[23,22], 'gender':['女','女']})
pd.concat([df1,df2] , keys = ['df1','df2'])
df2 = pd.DataFrame({'Name':['丁一','赵五'], 'age':[23,22], 'gender':['女','女']})
pd.concat([df1,df2])