Pandas实用案例操作总结(持续更新...)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29027865/article/details/83932778

一.实现一个功能:1.求出平均值;2.并在其列筛选出其大于平均值的数;

二.将分开的文件合并操作:

三.排序

四.找到多页面下的文章后,按照专栏名字进行对应,记录保存名字后的那些文章;

五.实现某列的去重,只保留其中一行的数据内容:

使用drop_duplicates方法来实现数据去重,实现方式如下:

test = test.drop_duplicates("标题"

六.删除某一列中含有’万’字的数字,并将其替换为数字:

test1 = test['bofang_num']
p = -1
for i in test['bofang_num']:
    p+=1
    if i.find("万") !=-1:
        print(i)
        i = i.replace("万","")
        i = float(i)*10000
        test['bofang_num'][p] = i
        print(i)
Series可以通过索引值来访问数值!

bool_index = test['bofang_num'].apply(lambda x:True if x.find("万")!=-1 else False)
test.loc[bool_index,"bofang_num"] = test['bofang_num'][bool_index].apply(lambda x:float(x.replace("万",""))*1000)

七.将表按照某一个特征值进行连接:

lis =["data_date_clean.csv","data_info_clean.csv","data_region_clean.csv","related_feature_table.csv"]
first = "Casualties_and_consequences.csv"
df1 = pd.read_csv(str(first),engine="python")   
for li in lis:
    df2 = pd.read_csv(str(li),engine="python")
    df1 = pd.merge(df1,df2,on="eventid")```

八.删除某列下含有缺失值或者指定值的样本

先将指定的样本值都替换维缺失值nan,再统一的删掉nan的数据

#删除缺失值以及为-99的数据
# test_shuzhi_chose.head()
# 将值替换为nan
test_shuzhi_chose_ca = test_shuzhi_chose.replace([int('-99')],[np.nan])
test_shuzhi_chose_ca[test_shuzhi_chose_ca['nperpcap']==-99]
# 再统一删除nan的值
test_shuzhi_chose_ca = test_shuzhi_chose_ca.dropna()

九.通过Pandas将每行的数据保存成csv文件:

# 在每行数据中,
item = {}
df = DataFrame()
for .....
   item['公司名称'] = html.xpath('//*[@id="wap_header_top"]/div[1]/div[1]/div[1]/text()')[0]
   df = df.append(item,ignore_index=True)
df.to_csv('text1.csv')

十.通过Pandas将文本txt转换为列表字符串:

company = pd.read_table('房地产商.txt',engine='python',header=None)
#此处注意,其实用company.values,也能达到列表字符串,但是它会少了第一行
#但是需要有headers=none,表示此文件无索引列名!
for i in company[0]:
    print(i)

十一.修改df列名

#将col_1的列名修改为col_a
df = df.rename(columns={'col_1': 'col_a'})

十二.根据key值进行合并

res = pd.merge(left, right, on='key')
#没有指定how的话默认使用inner方法
#how的方法还有:
#left
#只保留左表的所有数据
#right
#只保留右表的所有数据
#right
#只保留右表的所有数据
#inner
#只保留两个表中公共部分的信息

猜你喜欢

转载自blog.csdn.net/qq_29027865/article/details/83932778