您当前的位置: 首页 >  pandas

Better Bench

暂无认证

  • 2浏览

    0关注

    695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Pandas】Pandas Dataframe 常用用法

Better Bench 发布时间:2021-11-03 16:32:44 ,浏览量:2

在这里插入图片描述

(1)取某列等于某个值的所有行数据

df.loc[df['A']==999]

(2)datetime作为索引取行数据

# 第一种方式
df_index = list(df.index)
for index in df_index:
    tmp = df.loc[[str(index)]]
# 第二种方式
df_index = list(df.index)
for index in df_index:
	tag = df.loc[str(index),'B']

(3)取某列等于某个值的所有行

df = df[df.tag==False]

(4)合并list中的dataframe

df_list = [df1,df2,df3]
all_df = pd.concat(df_list)

(5)将某一列作为index索引

df.set_index(["Column"], inplace=True)

(6)根据index索引排序

df.sort_index(inplace=True)

(7)利用tqdm对一列进行处理

from tqdm import tqdm
tqdm.pandas()

def clearTxt(line):
    if line != '':
        line = line.strip()
        #去除文本中的英文和数字
        line = re.sub("[a-zA-Z0-9]", "", line)
        #去除文本中的中文符号和英文符号
        line = re.sub("[\s+\.\!\/_,$%^*(+\"\';:“”.]+|[+——!,。??、~@#¥%……&*()]+", "", line)
        #分词
        segList = jieba.cut(line, cut_all=False)
        segSentence = ''
        for word in segList:
            if word != '\t':
                segSentence += word + " "
    return segSentence.strip()
train_data['Text'].progress_apply(clearTxt)

(8)将city一列拆分为city1和city2两列

df['city1'] = df['city'].map(lambda x:x.split("|")[0])
df['city2'] = df['city'].map(lambda x:x.split("|")[1])

(9)属性列重命名

#方法一:修改列名a,b为A、B。
df.columns = ['A','B']
# 方法二
df.rename(columns={'a':'A'})

(10)删除有缺失值的行 删除空行

train.dropna(axis=0, how='any', inplace=True)

判断某行的值为空,值为nan

pd.isnull(value)

检查某行或某列的缺失值

df.isnull().any() 用来判断某列是否有缺失值
df.isnull().all() 用来判断某列是否全部为空值

(11)按日期datetime排序

Date,Last
2016-12-30,1.05550
2016-12-29,1.05275
2016-12-28,1.04610
2016-12-27,1.05015
2016-12-23,1.05005

df = pd.read_csv('data',sep=',')

print (df.head())
         Date     Last
0  2016-12-30  1.05550
1  2016-12-29  1.05275
2  2016-12-28  1.04610
3  2016-12-27  1.05015
4  2016-12-23  1.05005

df = df.sort_values(by = 'Date')
         Date     Last
4  2016-12-23  1.05005
3  2016-12-27  1.05015
2  2016-12-28  1.04610
1  2016-12-29  1.05275
0  2016-12-30  1.05550
df.reset_index(inplace=True)

del df['index']

print (df.head())
         Date     Last
0  2016-12-23  1.05005
1  2016-12-27  1.05015
2  2016-12-28  1.04610
3  2016-12-29  1.05275
4  2016-12-30  1.05550

(12)删除满足某条件的行

df_clear = df.drop(df[df['x']            
关注
打赏
1665674626
查看更多评论
0.0388s