懵懂的菜鸟

Stay hungry,Stay foolish.

导航

python数据分析开发中的常用整理

Pandas操作
python使用pandas读取csv

import pandas as pd
#数据筛选
usetTable = pd.read_csv(filename,header = 0)
mask = True ^ userTable['ID'].isin(['',''])&.....
show = userTable[mask]

#例子,包含6105的行
userTable[userTable['ID'].isin(['6105'])]
userTable[userTable['ID'].isin([6105])]

#统计某种数据出现的次数
result = userTable.group(['列名1''列名2']).size().result_index(name = 'count')

#表连接(列名一致)
result = pd.merge(result1,result2,how = 'left', on=['列名1''列名2'])
#表连接(列名不一致)
result = pd.merge(result1,result2,how = 'left', left_on = '列名',right_on = '列名')

#去除重复项
result = result1[~result1.duplicated(subset = ['列名1''列名2'], keep = 'last')]

#对指定项进行累加,展示
result = result1.groupby([])['count'].sum().reset_index()

#选取用户在不同地点的最大时间
result = result1.groupby([])['time'].max().reset_index()

#返回特定值的行
table[tabel.flag == 1]

#loc,iloc,ix
'''
loc通过标签索引读取行数据
iloc通过行号索引
ix结合两种
'''
#取某几列数据
iloc[:,[1,2]]

#python中的三元表达式
h = "变量1" if a>b else "变量2"
table.groupby('b').['key'].apply(lambda i: i.iloc[1] if len(i)>2 else len(i))#此处的i应用于每一行或每一列,自动匹配

#按照年龄排序
students = [('joh','A',15),('jat','B',12),('dev','B',10)]#tuple
list1 = sorted(students,key = lambda student:students[2])#list
sorted(cmp,key,reverse)#reverse默认为False,升序。

#过滤,每一行返回的是最大值
index1 = result.groupby()[].transform(max)
index2 = ( index1 == result['count'])

#取特定列
usetTable[['列名1','列名2']]
#删除特定列
userTable.drop('列名',axis =1)
axis = 0 表示沿着行标签方向执行方法
axis = 1 表示沿着列标签方向执行方法

#返回特定数据所在的行号
d = df[(df.Boolcol ==3 )& (df.attr == 32)].index.tolist()

#查看某几列的值
df.head(n)

#获取行号
raw = df.shape[0]

#通过行号获取其他数据
df.ix[d]['数据']

#list转array
np.array([list])

#array存为csv
pd.DataFrame(data = array).to_csv('yy',mode = 'a',header=False)

#获取某一列不重复的数据及个数
len(df['列名'].unique())

#python作图
#设置X轴
pd.set_index('列名')

pd.plot.line()

pd.random.randn(10,4)

fig, axes = plt.subplots(2,1)

pd.plot(kind ='bar', ax = axe[0])
#垂直柱状图
kind = 'bar'
#垂直密度图
kind = 'kde'
#水平柱状图
kind = 'barh'
#指定在某个子图上作图
ax = axe[0]
#生成堆积柱状图
stacked = True
#饼图
pd.plot.pie(subplots = True)

pd.plot.scatter(x = '列名',y = '列名')

#使用pd.Series把dataframe转成Series
pd.series(df['列名'].values,index = df[''])

#返回列数
userTable.colums.size

#将组内的列表合并,数据聚合
result = table.groupby(['id']).aggregate(lambda x: list(x))

#python去除字符串两端的符号
strip()去除首末
lstrip()去除左边
rstrip()去除右边

#把含有Nan的行删除
df.dropna()

#删除列为空的行
table =  pd.read_csv("", dtype = {'CUST_ID':str})
mask = table['CUST_ID'].isnull()
table = table[~mask]

#取列名
DataFrame.colums.values.tolist()

#转化为python可识别的数值
np.nan:nan
np.Inf:Inf

#对分组后的数据采取不同的运算方式
data = df.groupby('A')
data.agg({'B':'mean', 'c':'sum'})

#按照A分组后,对多列采取相同的聚合方式
df.groupby('A').apply(np.mean)

#将某列数据按数据值分成不同范围,进行分组运算
df = pd.DataFrame({'Age'}:np.random.randint(20,70,100),
                'sex':np.random.choice(['male','female'],size=(10)))

#生成时间格式
pd.dta_range('2018-6-20', periods =20, freq = '5min')

#按照范围分组
age_groups = pd.cut(df['age'], bins = [19,40,65,np.inf])
result = df.groupby(age_groups).max()

#生成交叉表
pd.crosstab(age_groups,df['sex'])

#分组后,转为dict
A = dic(list(df.groupby('key')))
A['a']

temp = df.groupby('type')
for name,group in temp:
    print(name)#str
    print(group)#DataFrame

fo x in temp:
    print(x)#tuple

agg使用:针对不同的列,应用不同的聚合函数
#按照A分组后,对另一列采取不同的聚合方式
df.groupby('A')['B'].agg({'mean':np.mean,'std':np.std})

#按照A分组后,对不同的列采取不同的处理方式
df.groupby('A').agg({'B':[np.mean,'sum'],'C':['count',np.std]})

#分组后,按照某几列排序
#按照时间排序
result.groupby(['a.id'],group_keys = False).apply(
                lambda g: g.sort_value('b.time',ascending = True))

#按照指定列排序
DF.sort_values(by = '列名', ascending = True)

#取某一列的值
tble['列名'].str[0:10]
#增加一列
table['new'] = talbe['列名'].str[0:10]

#lambda函数
my_lambda = lambda arg: arg+1
result = my_lambda(123)
等价于
def func(arg):
    return arg+1
result = func(123)

#读取csv问价
pd.read_csv(error_bad_lines = False(跳过错误行),
        quoting = CSV.QUOTE_NONE(指定字符使用时不收分隔符影响))

#pandas按照正则匹配
index = table['b.str'].str.contains(r'^\$.*')
result = table[index]

#获取特定值所在的列
result[result['a.id' == 2018]]
result[result['a.time' >= '2018-04-01']]
#保留第一次出现的行
df.drop_duplicates(subset = ['',''],keep='first')

 

posted on 2019-05-10 23:56  懵懂的菜鸟  阅读(1054)  评论(0编辑  收藏  举报