日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

dataframe,python,numpy 问题索引1

發(fā)布時間:2023/11/28 生活经验 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 dataframe,python,numpy 问题索引1 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
# 找出只有賭場數(shù)據(jù)的賬戶
gp=data.groupby(['查詢賬號','場景標簽'],as_index=True)
tj=gp.size().reset_index()按查詢賬號和場景標簽分組并統(tǒng)計數(shù)據(jù)條數(shù)

https://blog.csdn.net/weixin_38168620/article/details/79596819
fillna 填充
bb=aa.isnull().any()
print(bb)
20210712

某列有多少行非空數(shù)值統(tǒng)計:
統(tǒng)計所有列df.count()
單獨某列:df.age.count()

20210705

def apply_age(x,bias):return x+bias#以元組的方式傳入額外的參數(shù) #apply函數(shù)傳參的方式
data["age"] = data["age"].apply(apply_age,args=(-3,))def gender_map(x):gender = 1 if x == "男" else 0return gender#以元組的方式傳入額外的參數(shù)
data["age1"] = data["age"].map(gender_map)map不能傳參,apply 可以
apply 通過調(diào)節(jié) axis=0或者1來調(diào)節(jié)是對行還是列進行處理

https://zhuanlan.zhihu.com/p/100064394?utm_source=wechat_session
apply比map

20210628

ceshi=np.matrix([[1, 2], [1, 0]], dtype='int64') * np.matrix([[1], [0]])[[1, 2], [1, 0]]1  2
1  1
代表的是這樣的矩陣[[1], [0]]1
0
代表的是這樣的

20210625

         sent_len=len([j for i in sents for j in i])
for循環(huán)嵌套 第一層在前面

20210609

datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')

時間格式化

20210531

  peaks_df = pd.concat(peaks_list).reset_index(drop=True)#??

列表轉(zhuǎn)dataframe

20210528

        columns = ['no2', 'so2', 'co', 'o3', 'pm2_5', 'pm10']station_group_by_df['aqi'] = np.max(station_group_by_df[columns], axis=1)

批量求某列的最大值

pd.concat([pd.read_csv(f) for f in file_list]).reset_index()
concat和for循環(huán)的聯(lián)合使用

df.empty
判定一個df是否為空

https://vimsky.com/examples/usage/python-numpy.ufunc.reduce.html
python numpy ufunc.reduce用法及代碼示例
沿某個軸進行某個函數(shù)處理

>>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],[2, 3]],[[4, 5],[6, 7]]])
>>> np.add.reduce(X, 0)jz=[[1,2],[3,4]]
[1,2] 形狀為2行1列
[3,4] 形狀也為2行1列
np.minimum.reduce(jz)
等于 [1,2]
1  3
2  4
相當于每一行取最小值

x是一個多維矩陣,0可以為默認值不填

peaks = group.loc[group.index[peaks_index[0]], target]
按索引批量取出值

直接取出最大值所在的索引
https://blog.csdn.net/weixin_38605247/article/details/78736417
iterrows()對dataframe進行遍歷 按行遍歷

      df_mobile['time_internal']=(pd.to_datetime(df_mobile['published_at']) - pd.to_datetime(df_mobile['last_published_at'])) / timedelta(seconds=1)

這樣處理之后直接把結(jié)果變成了數(shù)值格式

type_dict = {‘lat’: ‘float’,
‘lon’: ‘float’,
‘co’: ‘float’,
‘so2’: ‘float’,
‘no2’: ‘float’,
‘o3’: ‘float’,
‘pm2_5’: ‘float’,
‘pm10’: ‘float’,
‘a(chǎn)qi’: ‘float’,
‘station_code’: ‘str’,
‘station_name’: ‘str’
}
exist_dict = {i: type_dict[i] for i in type_dict.keys() if i in data_df.columns}
data_df = data_df.astype(exist_dict)
批量修改列的類型

datetime
timedelta
timstamp

from datetime import datetime,timedelta

bb=pd.to_datetime(aa)
timestamp轉(zhuǎn)datetime

20210421

pandas transform
https://blog.csdn.net/kyle1314608/article/details/115943253

data['sum_price']=data.groupby('order')['ext_price'].transform('sum')

transform 的核?:作?于 groupby 之后的每個組的所有數(shù)據(jù)
并把結(jié)果追加到原表后面

df=pd.DataFrame({'id':[1,1,1,1,1,2,2,2,2,2],'name':['aa','aa','aa','bb','bb','aa','aa','bb','bb','bb'],'cls':['cc','cc','dd','dd','cc','cc','cc','dd','dd','cc'],'stu':[1,2,3,4,5,6,7,8,9,10]})df['sum_stu']=df.groupby(['id','name','cls'])['stu'].transform('sum')df['sqrt_stu']=df.groupby(['id','name','cls'])['stu'].transform(np.sqrt)
多列處理

( sum 可以換成任意的函數(shù) 甚至是自定義的函數(shù)
不一定把 )
20210420

https://blog.csdn.net/AaronPaul/article/details/106682486
長表轉(zhuǎn)寬表

pltj=pltj.pivot_table(
index=["ipo_province"],    #行索引(可以使多個類別變量)
columns=["relation"],                   #列索引(可以使多個類別變量)
values=["js"])                   #值(一般是度量指標)

寬邊轉(zhuǎn)長表

https://blog.csdn.net/qq_34535319/article/details/100601656
多級行索引轉(zhuǎn)成列

20210413

https://zhuanlan.zhihu.com/p/65147779
pandarallel


https://blog.csdn.net/jzlixiao/article/details/79583389
分箱 要覆蓋數(shù)據(jù)中的最小和最大值 否則會產(chǎn)生nan

20210407

追加保存 行之間錯位一般都是 concat的時候兩個表的索引沒對齊

series.values 直接轉(zhuǎn)numpy
dataframe.values 轉(zhuǎn)出來之后還多了個中括號
dataframe 單元格可以是直接array 可以直接存儲和讀出來是array
concat當兩個表的行數(shù)不一樣的時候,保留最大的行數(shù)(索引)

20210402

pandas.DataFrame.copy
DataFrame.copy(deep=True)
深度復制

https://blog.csdn.net/u012995500/article/details/109463219

并行parallel

20210315

https://blog.csdn.net/qq_24499417/article/details/81428594
pandas處理json

20210309

https://blog.csdn.net/weixin_44073728/article/details/111054157
pandas無法打開.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported

https://blog.csdn.net/u012193416/article/details/83152895
直接設(shè)定指定列為橫向索引
set_index


stack 左邊變成右邊
行索引變成二級列索引

sd=dd3.set_index(['spu','dateid'])[['active_sell']].unstack(level=-1).fillna(0)
列轉(zhuǎn)行
縱向改橫向https://www.cnblogs.com/rachelross/p/10439704.html綜上, 可以總結(jié), stack 的作用就是可以將橫向的表頭(列名)轉(zhuǎn)成縱向的索引列展示, 對于多行表頭而言, 具體要轉(zhuǎn)換哪一行取決于 level 參數(shù), 如果不指定, 則默認轉(zhuǎn)換最下面一行表頭. level 第幾級索引 從上往下數(shù)和從左往右數(shù)

df=pd.DataFrame({'a':['null',1]})
df[df['a']=='null']='no'
全表篩選并賦值cp1=cp.where(cp.notnull(), None)
dataframe的nan替換成Nonehttps://zhuanlan.zhihu.com/p/107050664
Series.where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False, raise_on_error=None)
如果 cond 為真,保持原來的值,否則替換為other, inplace為真則表示在原數(shù)據(jù)上操作,為False表明在原數(shù)據(jù)的copy上操作。mask方法與where方法作用相反,other默認為NaN
data_insert = [tuple(xi) for xi in last_merge.values] 
每行轉(zhuǎn)元組
metrics_save.groupby(['hy1','hy2'])['ndcg5'].mean().reset_index()
分組求平均

_temp = {‘job’:[‘farmer’, ‘teacher’, ‘worker’, ‘a(chǎn)cter’, ‘present’], ‘money’:[3000, 7000, 5000, 100000, 66666]}
df = pd.DataFrame(_temp)
print(df)

   job   money

0 farmer 3000
1 teacher 7000
2 worker 5000
3 acter 100000
4 present 66666
a = df[(df[‘money’]>10000)].index.tolist()
print(a)

[3, 4]

求滿足條件未知的索引

20210208

 i=0train=np.load('./20210202/company5_xiangl.npy',allow_pickle=True)# train=pd.DataFrame(train,columns=['other_company_ss', 'qymc_fss', 'qid','output_layer_fss', 'output_layer_ss' ])train=pd.DataFrame(train)from pandas_streaming.df import StreamingDataFramechunk= StreamingDataFrame.read_df(train, chunksize=5000)hz1=''k=0for ck in tqdm(chunk):data=ck.iloc[:,3:]hz=''j=0for i in tqdm(range(data.shape[0])):if j==0:per_row=np.hstack([np.frombuffer(data.iloc[i,0], dtype=np.float32), np.frombuffer(data.iloc[i,1], dtype=np.float32)])hz=per_rowhz=hz[np.newaxis,:]j+=1else:per_row = np.hstack([np.frombuffer(data.iloc[i,0], dtype=np.float32), np.frombuffer(data.iloc[i,1], dtype=np.float32)])per_row=per_row[np.newaxis, :]hz=np.concatenate([hz,per_row],axis=0)j+=1if k==0:hz1=hzk+=1else:hz1=np.concatenate([hz1,hz],axis=0)k+=1
分條處理的時候  在外面再套一層分塊

當兩個array之后列沒有行(也就是只有一個維度)的時候 用hstack 拼接
當兩個array都有兩個維度的時候 用concatenate

https://blog.csdn.net/weixin_42866962/article/details/82811082

numpy增加新維度

20210127

找出含空值的行 空行
https://www.jb51.net/article/169635.htm
直接用dropna

bb=aa.isnull().any()
print(bb)


得到每列的值是否存在null值

https://www.cnblogs.com/lucas-zhao/p/11697203.html
argsort
返回排序后的下標數(shù)組
def argsort(a, axis=-1, kind=None, order=None):axis : int or None, optionalAxis along which to sort.  The default is -1 (the last axis). If None,the flattened array is used.

20210122

            import randomaa=random.sample(['你','我'], 1)
中文隨機取值

– 空值:一種是從未填寫過數(shù)據(jù),二是填寫過數(shù)據(jù)后刪除掉的
– 第一種是null,第二種是’’
字符串的nan 用isnull 或者notnull 是不能處理的
數(shù)據(jù)庫

gl['prob']=gl['0_x']/gl['0_y']
gl['prob']=gl.apply(lambda x :round((x['0_x'])/(x['0_y']),2))
兩列操作 上面一種可以 下面一種不行 報 key錯誤
gp_ic=yuanqy.groupby(['industry','chain'],as_index=True)
ct_xi=gp_ic.size().reset_index()reset_index() 直接把groupy的索引恢復為從零開始排序的自然數(shù)列


右邊的形式通過 explode 處理后 得到右邊的形式 相當于寬表變長表
yuanqy=yuanqy.explode(‘chain’)

20210115

https://blog.csdn.net/Jfuck/article/details/9464959
numpy view 繼續(xù)看

aa=df.max(axis=0) 按每列統(tǒng)計
aa=df.max(axis=1) 按每行統(tǒng)計 等同于 df.max()

20210113

           x_train, x_test = x_data.iloc[train_index,:], x_data.iloc[test_index,:]y_train, y_test = y_data.iloc[train_index,:],y_data.iloc[test_index,:]train_index 是一個索引列表 只有 iloc 支持了
        cols = data.columns.tolist()# aa=cols.index('index')# bb=cols.pop(cols.index('index'))# aa=[1,2,3]# aa.insert(0,5)# aa.pop(0)insert_col=cols.pop(cols.index('index'))cols.insert(0,insert_col)data=data[cols]調(diào)整指定列index的位置
cols.insert(0, cols.pop(cols.index('Mid')))
調(diào)整列的順序
https://www.cnblogs.com/zhoudayang/p/5414020.html
df.iloc[:,2] 
df[[''col_name"]]
df.loc[:,2] 
上面三種選出來都是series 只有下面兩種方式選出來是dataframe
aa=df.iloc[1:2,:]
前面以區(qū)間的方式切片就可以得到dataframe而不是seriestb_vec=tb.iloc[:,2:]current_data =group.iloc[0,:].to_frame()current_data=current_data.T
    chunk=chunk.loc[chunk['output_layer_jyfw'].notnull(),:]剔除某列的空值

20210111

bq_bl = bq[0].to_numpy(dtype=np.int32)ValueError: invalid literal for int() with base 10: 'abc'
里面還沒有非數(shù)字字符的轉(zhuǎn)換

20210109

流式處理

20210108

https://blog.csdn.net/weixin_46165569/article/details/107146617
np.load 參數(shù)
np.savetxt 保存為為csv格式

data=pd.read_csv(path,iterator=False,chunksize=2,encoding='gbk')
for i in range(2):for chunk in data:print(chunk)分塊讀取 迭代器的形式占用的內(nèi)存很小設(shè)置了chunksize,iterator 可以不用管了for 一輪讀完之后就不能再for 了 只能把data= ...也同時放到for i.. 里面迭代器的作用就能分塊小批量地處理數(shù)據(jù)import pandas as pd
iter_csv = pd.read_csv('file.csv', iterator=True, chunksize=1000)
df = pd.concat([chunk[chunk['field'] > constant] for chunk in iter_csv])分塊中途處理后再合并

20210104

https://www.cnblogs.com/traditional/p/12629050.html
numpy增加維度

刪除只能刪除數(shù)組長度為1所對應(yīng)的維度,同理添加也是添加一個維度也只是讓數(shù)組在這個維度上的長度變成1,因為數(shù)組本來不存在這個維度的,但是我們強行加上了一個維度,那么數(shù)組在這個維度上的長度只能是1
import numpy as np
arr = np.array([[1, 2, 3], [2, 3, 4]])print(arr.shape)  # (2, 3)# 很好理解
print(np.expand_dims(arr, 0).shape)  # (1, 2, 3)
刪除維度
print(np.squeeze(arr, 0))

元組轉(zhuǎn)dataframe
sql execute 轉(zhuǎn) dataframe

20210103

https://www.jianshu.com/p/743b3bb340f6
布爾索引和花式索引

第一個中括號只管行,第二個中括號只管列?
第一個中括號的1代表第二行 0代表第一行
第一個中括號的1和第二個中括號的冒號配對? 為什么3,4會交換位置

20201229


內(nèi)存中字節(jié)數(shù)

a=np.array([1,2])
b=np.array([3,4])
print(a.dtype.itemsize)
查看單個元素在內(nèi)存中的字節(jié)數(shù)

datafarme 的元素可以是列表和數(shù)值 只是只能先用二進制的形式
存儲之后才能轉(zhuǎn)換成功?如何直接賦值單元格為列表或數(shù)組


train['output_layer_x']=train['output_layer_x'].apply(lambda x: np.frombuffer(x,dtype=np.float32))
train['output_layer_x']=train['output_layer_y'].apply(lambda x: np.frombuffer(x,dtype=np.float32))train['output_layer_x']=train['output_layer_x'].apply(lambda x: np.array(x))
train['output_layer_y']=train['output_layer_x'].apply(lambda x: np.array(x))train['output_layer']=train.apply(lambda x: np.concatenate([x['output_layer_x'],x['output_layer_y']],axis=0))
上面不能這樣操作train1['output_layer']=train1.apply(lambda x: np.concatenate([x['output_layer_x'],x['output_layer_y']]))hb=[]
for i in range(train1.shape[0]):print(i)temp=np.concatenate([train1['output_layer_x'].iloc[0],train1['output_layer_y'].iloc[0]],axis=0)hb.append(temp)
hb=np.array(hb)   hb列表直接轉(zhuǎn)成arraytrain['output_layer']=train['output_layer'].apply(lambda x:x.reshape(768,2))pandas和numpy的聯(lián)合處理  pandas的每個格子可以放數(shù)組
而且每個數(shù)組還可以直接進行數(shù)組的操作

20201227

https://www.jianshu.com/p/fc2fe026f002
reshape

https://blog.csdn.net/weixin_41797117/article/details/80048688
np_c
np_r
np.r_是按列連接兩個矩陣,就是把兩矩陣上下相加,要求列數(shù)相等。
np.c_是按行連接兩個矩陣,就是把兩矩陣左右相加,要求行數(shù)相等。
和vstack 以及hstack的區(qū)別是什么

20201225

tensor的索引也是取不到最大的一個 比如 [0:10] 取的索引是0 到 9 是取的10個值

指定替換和修改

ser.replace({0: 10, 1: 100})   重點
df = pd.DataFrame({'a': [0, 1, 2, 3, 4], 'b': [5, 6, 7, 8, 9]})
df.replace({'a': 0, 'b': 5}, 100)  #重點

20201222

數(shù)組的顯示方式和實際對應(yīng)的矩陣方向是相反的
看起來是水平 實際上是豎直的

20201219

https://blog.csdn.net/qq_36387683/article/details/87710821
np.tile(a,1) 1的位置可以是列表表示形狀也可以是標量
numpy 復制

X = np.expand_dims(df.values[:, 0:246].astype(float), axis=2)
[120 20] 編號是 0 1 然后變成 [120 20 1]
擴展新的軸

dataframe.iloc[0:i] iloc 是不包含i 的 如果是 指定寫i 則是包含i的

數(shù)組的數(shù)值類型更改

   xlb1 = xlb1.astype(np.float64)

list 的元素可以是array
numpy 拼接組合
https://blog.csdn.net/kyle1314608/article/details/111402520

20201218

dataframe 的元素不能是數(shù)組

import numpy as np
x = np.empty([3,2], dtype = int)
print (x)
https://www.runoob.com/numpy/numpy-array-creation.html
構(gòu)建多維數(shù)組

20201215

aa=np.random.choice(2) 隨機產(chǎn)生 0 到 1
numpy 隨機數(shù)
https://blog.csdn.net/kyle1314608/article/details/111273642

dataframe 因為性能而不能做的話 改成 numpy 可以處理

txwl=sxyxl_pqs.loc[((sxyxl_pqs['上游']==0) & (sxyxl_pqs['下游']==0)),: ]

每個條件都要用括號括起來

遇到有空值的時候
在控制臺把其內(nèi)容和類型打出來再針對性處理

20201214

這種空值對應(yīng) ‘’

https://blog.csdn.net/kyle1314608/article/details/111213976
刪除帶空值的行
拼接關(guān)聯(lián)的時候容易產(chǎn)生空值 nan
假設(shè)拿到一個10萬行的數(shù)據(jù)后,通過isnull我們發(fā)現(xiàn)某列有幾個空值,要把該列空值所在行刪除怎么操作?用dropna()會刪除所有有空值的行,請看下面實例。

    cfbc.drop(index=[10,23], inplace=True)

刪除指定行索引

列值篩選

    gys_filter1=df['supplier_name'].str.contains('供應(yīng)商')gys_filter2 = df['supplier_name'].str.contains('單位')df=df.loc[~(gys_filter1|gys_filter2),:]

20201210

X_768_3=pd.concat([X_768[‘qymc’],X_768_fl],axis=1,ignore_index=False)

兩個表索引沒對齊的情況下 需要加上 ignore_index=False?

  X_769['output_layer']=X_769['output_layer'].apply(lambda x:x[1:])不能這么用?最好像下面這樣用
Try using .loc[row_indexer,col_indexer] = value instead
 j_data.loc[j_data['season'] == '春', 'season'] = 'spring'

部分值的更改 也可以先把數(shù)據(jù)集分成幾個部分 再針對性處理之后 再合并

代碼跑半天都不出結(jié)果,而又看不到時間進度的時候
可以減少數(shù)據(jù)量測試 所用的時間 也可測試代碼是否可以跑通
這樣可以計算總體數(shù)據(jù)量跑完需要多少時間

np.where(_predict_binary(e, X) > thresh)
利用np.where實現(xiàn)篩選所需要的值

元組和列表一樣 都可以通過索引提取元素
比如
a=(1,2)
a[0]=1

找出列表中非零元素的索引

import numpy as np
a = [0, 1, 0, 1, 0, 0, 0, 0]
nonzeroind = np.nonzero(a)[0] # the return is a little funny so I use the [0]
print nonzeroind
[1 3][i for i, e in enumerate(a) if e != 0]

20201209

報錯的信息里面含有-1維度 很有可能需要再在外面加一個維度

csc_matrix
https://blog.csdn.net/kyle1314608/article/details/110929896

20201208

dataframe 以前筆記
https://blog.csdn.net/kyle1314608/article/details/110851107

loc iloc 區(qū)別
利用loc 來篩選的時候 中括號里面計算的值為 True,False 這種
https://blog.csdn.net/kyle1314608/article/details/110850700

20201207

https://editor.csdn.net/md/?articleId=110806128
字符映射為數(shù)字

sx=contrast.apply( lambda x: 1 if (x.loc[:,"test") == x.loc[:,"pred"] else 0]

上面為什么不行 注意后面是否加 axis=1
sx=contrast.loc[((contrast.loc[:,“test”]==1) | (contrast.loc[:,“pred”]==1)),:]
loc 篩選
sx不能改成contrast 等號兩邊的索引對不齊 只能用新的變量

20201204

X=train.iloc[:,:-1].astype(float)
-1是指的最后一列,這樣取是取不到最后一列的
dataframe 按索引取出記錄
X[train_index]
loc和iloc 在這里不行,train_index是一個列表
只有series才可以?dataframe 不行?

    result=data_set.groupby(lable,group_keys=False).apply(typeicalSampling,typeicalFracDict)

對每個group都利用typicalfracdict參數(shù)加入typicalsampling方法中進行處理

具體查看這里
https://blog.csdn.net/kyle1314608/article/details/110085693

20201202


一行或者一列的時候 中括號里面的元素是用逗號分開的,多行或多列的時候不是?

IndexError: single positional indexer is out-of-bounds
iloc[i] 傳入的i 大于實際值個數(shù)的范圍

ndarray 中的中括號[]不是列表 列表中的元素是以逗號隔開

import numpy as np
arr=[1,2,3,4,5]
np.save(‘test’,arr)# 將數(shù)組以二進制格式保存到磁盤
#讀取
print(np.load(‘test.npy’))#[1 2 3 4 5]

npy文件

20201130

‘0’ 在 IDE dataframe 預覽中顯示這樣的情況則表示實際上外面還有一對
雙引號 比如“‘0’” 無法直接轉(zhuǎn)成 數(shù)值 只有預覽顯示為0的時候才能
轉(zhuǎn)換成數(shù)值

使用map的方法就可以實現(xiàn)把某一列的字符類型的值轉(zhuǎn)換為數(shù)字。
class_mapping = {‘A’:0, ‘B’:1}
data[class] = data[class].map(class_mapping)

在ndarray 顯示為 元素為向量的時候 實際上每個元素是分別在一列中
而不是一個向量的所有元素在一個單元格中

多個字符串轉(zhuǎn)元組
先 用逗號分開,然后用split分成列表,然后再把列表轉(zhuǎn)成元組

https://blog.csdn.net/kyle1314608/article/details/110434419
重命名

X=X[‘embeding’].str.split(’,’, expand=True)
https://blog.csdn.net/kyle1314608/article/details/110428430
合并的成一個單元格的時候可以先把行轉(zhuǎn)為列 然后再轉(zhuǎn)為 list
拆分分裂

pandas-兩個Series拼接合并為一個DataFrame(pd.concat)
a_series = pd.Series([“a”, “b”, “c”], name=“Letters”)
another_series = pd.Series([1, 2, 3], name=“Numbers”)
df = pd.concat([a_series, another_series], axis=1)
#merge a_series and another_series
print(df)
OUTPUT
Letters Numbers
0 a 1
1 b 2
2 c 3

gl1cp[‘encodedata’]=gl1cp[‘encodedata’].apply(lambda x:re.sub(r"\n","",x))gl1cp[‘encodedata’]=gl1cp[‘encodedata’].apply(lambda x:re.sub(r"\n","",x))

字符中換行符的匹配和替換

aa=’[1.1,2.1]’
aa=aa.replace("[","")
aa=aa.replace("]","")
aa=aa.split(",")
aa= [float(i) for i in aa]

字符轉(zhuǎn)列表

gl1cp[‘split’].iloc[i].remove(’’)
gl1cp[‘encodedata’]=gl1cp[‘encodedata’].apply(lambda x:x.remove("’’,"))
列表的remove 沒有返回值 不能用等號
也不能寫到apply 里面

字符串 直接外面加 list(“你們好”) 會得到上面的形式

gl1cp[‘split_tuple’].iloc[i]=tuple(gl1cp[‘split’].iloc[i])

dataframe 單元格不能保存元組?

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer(classes = [‘光伏電站發(fā)電’, ‘光伏電站’, ‘光伏組件’, ‘光伏電站工程’, ‘光伏應(yīng)用系統(tǒng)’, ‘光伏硅片’])
zh=mlb.fit_transform([(‘光伏電站發(fā)電’, ‘光伏電站’), (‘光伏組件’,),(‘光伏電站工程’,)])

單個元素的后面要加逗號,兩個以上的后面不用加逗號
https://blog.csdn.net/kancy110/article/details/75094179
多標簽轉(zhuǎn)換為二者型

group[‘split’].loc[:].to_list()

一個方括號取出來是series 要統(tǒng)計個數(shù)先轉(zhuǎn)化成list
然后用len 求列表元素個數(shù)

mydf.dropna(subset=[‘列名’],inplace=True)
刪除含空值的行

numpy 序列化

np.frombuffer(x.dtype=np.float32) 二進制 轉(zhuǎn)換成原來的格式

np.tobytes(a) 轉(zhuǎn)成二進制 貌似是錯的

20201124

dataframe 以tab鍵分列保存

不要直接打tab鍵上去
正則的表達方式

https://editor.csdn.net/md/?articleId=110085693
python抽樣,采樣

https://blog.csdn.net/kyle1314608/article/details/110086248
dataframe抽樣

https://blog.csdn.net/kyle1314608/article/details/110085354
樣本劃分 數(shù)據(jù)集劃分

字符replace
https://www.runoob.com/python/att-string-replace.html

for 循環(huán)的時候 剛開始會引入亂符,可以事先不用處理
等最后for循環(huán)完了之后再統(tǒng)一一次處理

20200724
data = data.apply(pd.to_numeric, errors=‘ignore’)
應(yīng)用時候忽略錯誤
20200719
TypeError: ‘Series’ objects are mutable, thus they cannot be hashed

result_quan.iloc[result_quan[‘相似度’]==1,‘包含’]=1
loc沒寫
loc[行,列]
loc是兩部分
20200707

https://editor.csdn.net/md?articleId=107187574
對列表元素去重并保持原來順序

20200624

https://blog.csdn.net/weixin_43368684/article/details/88756103
列中不包含某個字符

df[df[“col”].str.contains(‘this’|‘that’)==False]
df = pd.DataFrame({“A”: [“Hello”, “this”, “World”, “apple”]})
df[df[‘A’].str.contains(“Hello|World”)==False]
A
1 this
3 apple

20200618

https://www.cnblogs.com/liulangmao/p/9301032.html
shift
pandas DataFrame.shift()函數(shù)可以把數(shù)據(jù)移動指定的位數(shù)
period參數(shù)指定移動的步幅,可以為正為負.axis指定移動的軸,1為行,0為列.

20200527

空表添加行數(shù)據(jù)

        if (biaonr.shape[0]<shujhs)&(biaonr.shape[0]==0):xianzhs=biaonr.shape[0]buchs=shujhs-xianzhscolmc=biaonr.columnschuszd = {}for i in colmc:      #如果是空表,先人工補充一行數(shù)據(jù)chuszd[i]='人工填充'renggz=pd.DataFrame(chuszd,columns=biaonr.columns,index=[0])biaonr=pd.concat([biaonr,renggz],axis=0,ignore_index=True)

https://blog.csdn.net/roamer314/article/details/80886075

20200518

zdlx=[ i if i in biaonr.columns else ‘’ for i in zdlx.tolist()]
zdlx=sorted(zdlx)
zdlx=set(zdlx)
zdlx=list(zdlx)
zdlx=zdlx[1:]

列表中剔除某些元素

列表追加轉(zhuǎn)為dataframe

20200516

[ i if ‘pb’ in i else ‘’ for i in ycjg.columns ]
[ i for i in ycjg.columns if ‘pb’ in i ] 過濾
列表生成式

20200515

perr=zengq.iloc[i:i+1,:]
加個冒號直接取出來就是dataframe 不是series 不需要再轉(zhuǎn)換

fg[‘col_name’]=fg[‘col_name’].apply(lambda x:x.lstrip())
fg[‘comments’]=fg[‘comments’].apply(lambda x:x.lstrip())

去除單元格左邊空格

20200514


dataframe 累乘是向下累乘

當單元格的值是列表或者元組的時候,分組聚合運算會出問題

In [25]: gb = df.groupby(‘gender’)
In [26]: gb.
gb.agg gb.boxplot gb.cummin gb.describe gb.filter gb.get_group gb.height gb.last gb.median gb.ngroups gb.plot gb.rank gb.std gb.transform
gb.aggregate gb.count gb.cumprod gb.dtype gb.first gb.groups gb.hist gb.max gb.min gb.nth gb.prod gb.resample gb.sum gb.var
gb.apply gb.cummax gb.cumsum gb.fillna gb.gender gb.head gb.indices gb.mean gb.name gb.ohlc gb.quantile gb.size gb.tail gb.weight

分組聚合運算類型
分組累乘之后 索引會自動改成數(shù)字序列?

https://blog.csdn.net/zxyhhjs2017/article/details/93498104?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-30.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-30.nonecase

累乘

dataframe 中某列是元組 使得dataframe 不能顯示出來?

gp=duiying.groupby([‘qian’,‘hou’],as_index=True)
pltj=gp[‘hou’].count()

pltj=pltj.to_frame(name=‘num’)
pltj.index=range(pltj.shape[0])
pltj[‘index’]=list(pltj.index)

分組統(tǒng)計之后 多層索引轉(zhuǎn)換為列

20200423

求各行的和各列的和
https://my.oschina.net/u/2306127/blog/1920367
DataFrame數(shù)據(jù)預覽
計算各列數(shù)據(jù)總和并作為新列添加到末尾
df[‘Col_sum’] = df.apply(lambda x: x.sum(), axis=1)
計算各行數(shù)據(jù)總和并作為新行添加到末尾
df.loc[‘Row_sum’] = df.apply(lambda x: x.sum())
最終數(shù)據(jù)結(jié)果:

  data_=data_[data_.columns[0:-1]]

通過列名取出來一列還是dataframe 不用再從series轉(zhuǎn)換

https://www.cnblogs.com/zhoudayang/p/5564219.html
https://blog.csdn.net/cow66/article/details/100119058
重點
同時對多列進行操作

ycjg[str(j)+‘pb’] = ycjg.apply(lambda x:x[str(j)] ==x[‘mubc’],axis=1)

apply括號里面的x 代表前面?zhèn)魅氲氖?ycjg dataframe
要每個元素單獨比較 axis=1 每列的每個元素對應(yīng)比較
axis=0 每行的元素對應(yīng)比較
多列比較 兩列比較 兩列操作

df[‘duplication’]=df.apply(lambda x: 1 if ((x[0]==x[1])) else 0 ,axis=0 )
只能是X[0] 這種形式,不能用x[‘mubc’]的形式

df[df[‘target’]==‘脈搏’]

直接df通過true false 來篩選的時候,篩選的是整行
20200414
字符轉(zhuǎn)換為數(shù)值

https://www.cnblogs.com/sench/p/10134094.html
from sklearn import preprocessing
le = preprocessing.LabelEncoder() #獲取一個LabelEncoder
le = le.fit([“male”, “female”]) #訓練LabelEncoder, 把male編碼為0,female編碼為1
sex = le.transform(sex) #使用訓練好的LabelEncoder對原數(shù)據(jù)進行編碼
print(sex)

20200413
行追加用append,concat
列插入 用 insert

# X.iloc[:, i_outlier] = X.iloc[:, i_outlier].astype(float)

類型轉(zhuǎn)換花的時間很多!

20200410

https://blog.csdn.net/uvyoaa/article/details/79157786
分組取前n行

https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html
groupby api

grouped = df.groupby([‘class’]).head(2)
分組取前面幾條
goupby之后就是對每類分別操作?

https://blog.csdn.net/The_Time_Runner/article/details/84076716
set_index:刪除原來索引,并用新的數(shù)字列覆蓋索引
reset_index:drop false 將原來的索引加入當前df作為列 同時用數(shù)字改寫行索引
drop true 不作為列 同時用數(shù)字改寫行索引

reset_index()

test_data.groupby(‘release_year’)[‘genre’].value_counts()
分組對某列計數(shù)

注意篩選條件最終的表現(xiàn)形式是True或False

看起來是相同的但是實際上有個有空格,導致分組統(tǒng)計的時候
會出現(xiàn)兩個值

gb=df.groupby([‘target’],as_index=True)
gb_count=gb.size() 是series
對分組列本身值統(tǒng)計計數(shù) 如圖在上

不是size 而count的結(jié)果會把所有列索引保留

https://blog.csdn.net/meiqi0538/article/details/82533456
series 追加,添加值

列名的更改
df.rename(columns={‘原列名’:‘新列名’}, inplace=True)

append,concat 出問題 基本上就是兩張表的行或者列索引
不一致導致的

20200408

ValueError: column index (256) not an int in range(256)
https://www.cnblogs.com/z-x-y/p/9639702.html

sigle_col=group.loc[i_gp, :]
sigle_col=(sigle_col.to_frame()).T
series 轉(zhuǎn)dataframe

20200407
(df_test.loc[df_test.loc[:,‘列1’]==‘你好’,‘列1’])=‘大哥’
篩選 賦值 注意大圓括號 不能少
series或者dataframe 才能賦值 如果加iloc[0] 反而不能賦值

20200326
分組排序
df=df.groupby(‘LABEL1’).apply(lambda x:x.sort_values(‘行數(shù)’)).reset_index(drop=True)
test2=df_test.sort_values([‘列2’,‘列3’],ascending=[True,True])

兩種效果是一樣的

20200325


statis.to_excel(path + ‘統(tǒng)計結(jié)果_’ + str(i_sam) + ‘.xls’)
前面的to_excel 如果和后面的xls 不對應(yīng)的話
輸出就會像上面的錯誤

dataframe 模糊的 是df 進行比較 沒取到具體的值

20200322

def dot_index(x):dot_index=re.search(r'\.',str(x)).span()[0]return dot_index
df['len'] = df.iloc[:, i].apply(lambda x: 1 if ((x!=0)&(int(str(x)[(dot_index(x)+1):]) ==0) & (len(str(int(x)))==1)) else 2)

某個字符所在的索引,判斷是否是個位數(shù)

for i_outlier in tqdm(range(df_.shape[1])):
# print(i_outlier)
min_ = np.percentile(df_.iloc[:, i_outlier], 0.5, interpolation=‘lower’)
max_ = np.percentile(df_.iloc[:, i_outlier], 99.5, interpolation=‘higher’)
filter=df_.iloc[:, i_outlier][(df_.iloc[:, i_outlier] > max_) | (df_.iloc[:, i_outlier] < min_)]
df_.iloc[:, i_outlier][(df_.iloc[:, i_outlier] > max_) | (df_.iloc[:, i_outlier] < min_)] = 0
dataframe 大部分都是索引問題
如果for 的指和索引相同 且索引存在重復時候,第四行將會改變所有相同的索引

20200321
min_ = np.percentile(df_.iloc[:, i_outlier], 0.5, interpolation=‘lower’)
max_ = np.percentile(df_.iloc[:, i_outlier], 99.5, interpolation=‘higher’)

filter=df_.iloc[:, i_outlier][(df_.iloc[:, i_outlier] > max_) | (df_.iloc[:, i_outlier] < min_)]
有可能取出來是空值,最小和最大的值的個數(shù)都很多
這樣就篩選不出來

20200320
df_sample.loc[0seg:1(seg-1),str(i_1000)]=fuzhi #劃分出的數(shù)據(jù)加到sample表,復制用dataframe不行,series 才可, 左右兩邊形式相同
series=series
dataframe=dataframe
20200319
df.loc[True]
df[True] 二者皆可以

20200319
df = df.loc[~df.iloc[:, 0].str.contains(‘心率’), :]
series 判斷是否包含某些字符
20200318

df=df[~df[col_name[0]].isin([‘0’, ‘0.0’, ‘’])]
判斷某列是否含有某值

20200317
X_train = df_train.iloc[:,0:-1]
索引-1 為最后一列

20200313
空值
isna() 不能識別’’

替換成‘’,篩選的時候用 aa==‘’

excel里面的空白,讀到dataframe 里面是不存在的
無法顯示出來的,比如本來一列有10行,有兩個空白
讀入之后就只剩下8個數(shù)據(jù),兩個空白無法顯示出來

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
(sigcol0.iloc[0] + sigcolna.iloc[0]) + sigcol00.iloc[0] > df.shape[0] * 0.5
sigcol0 是series 不能 sigcol0>15 不能直接判斷
必須把值取出來再判斷

apply 只適合于apply

20200311

https://blog.csdn.net/qq_22238533/article/details/70917102

            np.random.shuffle(data)dataframe不能用np的shuffle
from sklearn.utils import shuffle
df = shuffle(df)

隨機打亂 打散
concat 合并 行或者
列索引不相同就會產(chǎn)生錯誤

df.notna() 非空值
dataframe 整體選擇
df=df[df!=0] 零的部分變成nan,因為其要保存整體索引的不變
df=df[df.isna()] 這樣好像是不起作用的
即使是按列來操作也是不行的,因為其要按最多值的列的索引
來concat 最終還是達不到只刪除空值,非空值自動靠攏的目的


為什么非空值選不出來

20200310
指定位置插入列
df_minmax.insert(loc=0,column=‘784’,value=’’)

   df_sample=pd.DataFrame({'0':[0]*seg},index=[0]*seg)創(chuàng)建

正則要刪除 “…” 主要"."是通配符,需要轉(zhuǎn)義
re.sub(r’…’, ‘.’, x) 替換的部分就不用轉(zhuǎn)義了 in_file=in_file.loc[in_file.iloc[:,0]!= ‘.’] #去掉純粹的點號
后面的等號是指整個字符為一個點號

pandas series 方法
df2 = df[df[columnname].str.contains(area)] 就是選擇包含area變量中的字符串的行。

20200309
quantity=former_data.loc[former_data[‘target’]==target_,‘quantity’]
dataframe 篩選
只有l(wèi)oc 才有上面那種用法 相當于前面指定行,后面指定列
df整體只能是整行整行的篩選

csv 沒有行數(shù)限制
xlsx 最高一百多萬行

20200306

寫條件判斷的時候,多條件組合的所有情況
還有最邊上的情況要考慮完全



xlsx輸出變成了這樣,csv 輸出則為正常

df.sample.columns = [[df[‘target’].iloc[i]]]
columns 等于的值 對象是列表的列表

numpy,ndarray,dataframe 行列的對應(yīng)

20200305
刪除 test_dict_df.drop([‘id’],axis=1)

dataframe 的坑
data_df=data_df.dropna(thresh=0.5*data_df.shape[0],axis=0)
這里的閾值一定要設(shè)置 不然 一旦有一個值為空 整個都會被刪掉
20200304

df.iloc[:, i_outlier][(df.iloc[:,i_outlier]>max_) or (df.iloc[:,i_outlier]<min_)]= 0
or 的前后必須加括號 不然 就會默認 max _和or運算

對每一行和每一列進行循環(huán)處理好像只能for循環(huán)
而對每一行或者每一列里面的每個值進行處理 則可以增加一行
或者一列來處理 不用for循環(huán)

20200303
iloc 不能用于擴展,會報溢出錯誤
而loc可以直接添加行或者列
dataframe 的index 本身是個array 對象

https://blog.csdn.net/qwertyuiop5rghar/article/details/84454670
https://blog.csdn.net/qwertyuiop5rghar/article/details/84454670
增加行 只能用 loc? 不能用iloc
擴充數(shù)據(jù)的時候 用增加行比增加列容易

http://www.voidcn.com/article/p-fnoxvztw-bxs.html
用字典隨機填充數(shù)據(jù)


填充的時候前后的形狀要對齊

缺失值填充
https://blog.csdn.net/donghf1989/article/details/51167083/

20200302
def sort_handling(self, df):
df_=df.astype(float)
for i_col in df_.columns:
temp_sort=df_.loc[:, i_col].sort_values()
temp_sort.index=range(temp_sort.shape[0])
df_.loc[:, i_col] = temp_sort #排序后索引沒對齊 需要重新更改索引
每列單獨排序

       df_.loc[:, i_col] = df_.loc[:, i_col].sort_values()  #排序后索引沒對齊 需要重新更改索引索引對不齊 執(zhí)行不成功 需要更改索引

20200302
找出nan以及inf
https://blog.csdn.net/alanguoo/article/details/77198503

20200228

numpy數(shù)據(jù)類型dtype轉(zhuǎn)換
https://www.jianshu.com/p/a1da90edf87f

dataframe 所有值篩選
df=df[df!=0]

20200226

在類里面 調(diào)用其中的某個函數(shù)時候用self.aa()
不能是在類內(nèi)部,應(yīng)該是在 某個函數(shù)內(nèi)部才能調(diào)用self

字符到數(shù)值的映射
https://blog.csdn.net/liulunyang/article/details/88089962

dataframe 增加列 insert

https://blog.csdn.net/W_weiying/article/details/85247436

dataframe array 相互轉(zhuǎn)換

20200225

df[‘舒張壓.17’]=df[‘舒張壓.17’].apply(lambda x: ‘’ if 1-bool(x.isdecimal()) else x)
1-bool(a) True 和 False的轉(zhuǎn)換
if 的前面空值,直接寫‘’,不用寫x=‘’ 隱含已經(jīng)有x=了
https://blog.csdn.net/laoyuanpython/article/details/94214189
判斷是否為數(shù)值

df_sort[‘身高’][df_sort[‘身高’]<38.0]=int(df_sort[‘身高’].mean())
某一列中選出某些值 然后統(tǒng)一更改 左邊中括號里面得到的是索引
df[col][df[col] >limit]=df[col][df[col] >limit]/1000
批量處理

列名稱的改寫
data_df.columns=[df['label'].iloc[i]]    

20200224 空值或者Nan的選擇
重點
對于不確定是什么樣的空值
https://www.cnblogs.com/wqbin/p/12032073.html
data_df_not_nan=data_df[data_df!=‘NaN’]
data_df_non = data_df[data_df ==‘NaN’]
data_df_1=data_df[~data_df.isnull()]
上面是針對值為none的過濾
對NaN的處理 用dropna?
https://blog.csdn.net/xu136090331/article/details/94784021 這個是重點
https://www.jianshu.com/p/ab64424ee99e

上面兩種為什么不起作用
https://blog.csdn.net/lwgkzl/article/details/80948548
空值的處理

df.dropna()
df[‘舒張壓.17’][df[‘舒張壓.17’]==’’] = 0
如果是空白 那用‘’處理

版權(quán)聲明:本文為博主原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接和本聲明。 本文鏈接:https://blog.csdn.net/luolang_103/article/details/88898526

參考:

(3條消息)pandas中的DataFrame按指定順序輸出所有列 - quintind的專欄 - CSDN博客
https://blog.csdn.net/quintind/article/details/79691574

(1)創(chuàng)建數(shù)據(jù)框:

  1. import pandas as pd
  2. grades = [48,99,75,80,42,80,72,68,36,78]
  3. df = pd.DataFrame( {'ID': ["x%d" % r for r in range(10)],
  4. 'Gender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'],
  5. 'ExamYear': ['2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'],
  6. 'Class': ['algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'],
  7. 'Participated': ['yes','yes','yes','yes','no','yes','yes','yes','yes','yes'],
  8. 'Passed': ['yes' if x > 50 else 'no' for x in grades],
  9. 'Employed': [True,True,True,False,False,False,False,True,True,False],
  10. 'Grade': grades})
  11. print(df)

?輸出:

?

(2)整理按指定列輸出?

代碼:

  1. col = ['Grade','Passed','ID','Class','Gender','Participated','Employed','ExamYear']
  2. df=df.ix[:,cols]

?輸出:

(3) 數(shù)據(jù)框轉(zhuǎn)化成列表

方法一:

? ?借助數(shù)組 ??

  1. import numpy as np
  2. df = np.arrary(df)
  3. df1 = df.tolist()

方法二:

df1 = (df.values).tolist()

輸出結(jié)果:

?(4)數(shù)據(jù)框中某一列的值轉(zhuǎn)化為字符串

?

  1. df2 = (df.values).tostring()
  2. df3 = (df['ID'].values).tostring()

輸出: ?

?

不懂為啥是這個樣子

?

希望的樣子:

代碼:

  1. df4 = tuple(df['ID'])
  2. df5 = str(df4)

?輸出:

datafram 轉(zhuǎn) list

-- coding:utf-8--

import numpy as np
import pandas as pd

data_x = pd.read_csv(“E:/Tianchi/result/features.csv”,usecols=[2,3,4])#pd.dataframe
data_y = pd.read_csv(“E:/Tianchi/result/features.csv”,usecols=[5])

train_data = np.array(data_x)#np.ndarray()
train_x_list=train_data.tolist()#list
print(train_x_list)
print(type(train_x_list))

-- coding: utf-8 --

“”"
Created on Sat Jul 21 20:06:20 2018

@author: heimi
“”"
import warnings
warnings.filterwarnings(“ignore”)
import pandas as pd
import numpy as np
#導入自定義模塊
import sys
from pandas import Series,DataFrame
from numpy import nan as NA
from os import path

sys.path.append( path.dirname(path.dirname(path.abspath(file))))

import mytools.midtools as midtools
from matplotlib.font_manager import FontProperties
#顯示中文
font=FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
path=r’D:/code12temp/自己筆記/’
pd.set_option(‘display.width’,None)

Series數(shù)據(jù)的連接

s1 = Series([0,1],index=[“a”,“b”])
s2 = Series([2,3,4],index=[“c”,“d”,“e”])
s3 = Series([5,6],index=[“f”,“g”])
result = pd.concat([s1,s2,s3])
result

result = pd.concat([s1,s2,s3],keys=[“one”,“two”,“three”])
result
#直接在外面再追加一層索引

#合并重疊數(shù)據(jù)
a = Series([NA,2.5,NA,3.5,4.5,NA],index=list(“fedcba”))
b = Series(np.arange(len(a)),dtype=np.float64,index=list(“fedcba”))
pd.concat([a,b])

#用其中一個Series中的數(shù)據(jù)給另一個Series中的數(shù)據(jù)作為補丁
resultB = b[:-2]
resultB
resultA = a[2:]
resultA
resultB.combine_first(resultA) #二者索引相同的時候 用ResultB的索引優(yōu)先

而且B的元素為NAN的,通過A中有點來填充,B 中沒有的,A中有的,直接填上

反正就是A的元素只會增加,不會減少

#創(chuàng)建層次化索引 兩層索引
data = Series(np.random.randn(10),index= [list(“aaabbbccdd”),[1,2,3,1,2,3,1,2,2,3]])
data

將行索引(index)轉(zhuǎn)換到列索引上(columns) 沒行列

result = data.unstack()
result
result.stack()

DataFrame 中的行索引和列索引的重塑和轉(zhuǎn)換

data = DataFrame(np.arange(6).reshape(2,3),
index=pd.Index([“上海”,“北京”],name=“省份”),
columns=pd.Index([2011,2012,2013],name=“年份”))
data

將DataFrame的列索引轉(zhuǎn)化到行索引 烈士

result = data.stack()

#將DataFrame的行索引轉(zhuǎn)化為列索引
#unstack()默認轉(zhuǎn)換的最內(nèi)層的層次化索引
result.unstack()
#第一種方法,轉(zhuǎn)換的時候,指定層次化索引的名稱
result=result.unstack(“省份”) #相當于交換了行列
result.stack()

#第二種方法,轉(zhuǎn)換的時候,指定層次化的索引 0是result的第一列,1是后面一層
data=result.unstack(1)
data.unstack(1)

#在對DataFrame進行unstack操作時,作為旋轉(zhuǎn)軸的級別將會成為結(jié)果中的最低級別
data = DataFrame(np.arange(6).reshape(2,3),
index=pd.Index([“Ohio”,“Colorado”],name=“state”),
columns=pd.Index([“one”,“two”,“three”],name=“nu mbers”))
data
result = data.stack()

df = DataFrame({“l(fā)eft”:result, #直接以series 為對象 并帶來了行索引
“right”:result+5},
columns=pd.Index([“l(fā)eft”,“right”],name=“side”))
df

result = df.unstack(“state”) #放到原來索引的下一層

s1=Series([0,1,2,3],index=list(“abcd”))
s2 = Series([4,5,6],index=list(“cde”))
#將s1和s2拼接成一個具有層次化索引的Series
result = pd.concat([s1,s2],keys=[“one”,“two”])
result
#將結(jié)果中的行索引變成列索引 #多層索引序號以零開頭
tempResult = result.unstack(1)
tempResult

#全部還原,空值用NaN填充
tempResult.stack(dropna=False)

3、pandas高級應(yīng)用–數(shù)據(jù)轉(zhuǎn)化、清除重復數(shù)據(jù)

data = DataFrame({“k1”:[“one”]*3+[“two”]*4,
“k2”:[1,1,2,3,3,4,4]})
#第一種方法,去重
#檢測DataFrame中的每行數(shù)據(jù)是否為重復數(shù)據(jù)行
mask = data.duplicated() #當前行的記錄和上一行記錄進行比較
mask

#通過花式索引去除重復的數(shù)據(jù)
data[~mask] #保留為false的

#第二種方法:去重
#通過DataFrame內(nèi)置的drop_duplicates()方法去除重復的數(shù)據(jù)行.
#去除

data.drop_duplicates()
data[“v1”] = range(7)

只以k1這一列為標準去重

data.drop_duplicates([“k1”])

#通過制定keep參數(shù)制定需要保留特定的重復數(shù)據(jù)
#keep=“first” 保留重復數(shù)據(jù)第一次出現(xiàn)的行索引
#keep=“l(fā)ast” 保留重復數(shù)據(jù)最后一次的行索引
#keep=False 只要有重復數(shù)據(jù),就全部丟掉

data=DataFrame({‘food’:[‘bacon’,‘pulled pork’,‘bacon’,‘Pastrami’,
‘corned beef’,‘Bacon’,‘pastrami’,‘honey ham’,‘nova lox’],
‘ounces’:[4,3,12,6,7.5,8,3,5,6]})

meat_to_animal={
‘bacon’:‘pig’,
‘pulled pork’:‘pig’,
‘pastrami’:‘cow’,
‘corned beef’:‘cow’,
‘honey ham’:‘pig’,
‘nova lox’:‘salmon’}
data[“animal”]=data[“food”].map(str.lower).map(meat_to_animal)
data[“animal”] = data[‘food’].map(lambda x: meat_to_animal[x.lower()])
#這里的x.lower相當key了

4、pandas高級應(yīng)用–數(shù)據(jù)替換

series = Series([1,-999,2,-999,-1000,3])
#單個數(shù)據(jù)替換
series.replace(-999,NA)
#多個數(shù)據(jù)替換
series.replace([-999,-1000],NA)

#replace方法傳入字典,針對不同的值,進行不同的替換
#第一種方法
series.replace({-999:NA,-1000:0})

#第二種方法
series.replace([-999,-1000],[NA,0])

5、pandas高級應(yīng)用–數(shù)據(jù)拆分

from matplotlib import pyplot as plt

age = [20,22,25,27,21,23,37,31,61,45,41,32]
#將所有年齡進行分組
bins = [18,25,35,60,100] #前開后閉
#使用pandas中的cut對年齡數(shù)據(jù)進行分組
cats = pd.cut(age,bins)

#調(diào)用pd.value_counts方法統(tǒng)計每個區(qū)間段的人數(shù)
pd.value_counts(cats) #直接統(tǒng)計

#區(qū)間屬于那一行索引 按大小排序的
cats.codes

#為分類出每一組年齡加上標簽
group_names = [“Youth”,“YouthAdult”,“MiddleAged”,“senior”]

#用group_name中的值,把區(qū)間替換
personType = pd.cut(age,bins,labels=group_names) #為什么這里不對

plt.hist(personType)
plt.show()

06、pandas高級應(yīng)用–數(shù)據(jù)分割

data = np.random.randn(1000) # 服從正太分布
result = pd.qcut(data,4) # cut將data數(shù)據(jù)均分為4組
result

統(tǒng)計落在每個區(qū)間的元素個數(shù)

pd.value_counts(result)

cut函數(shù)分割一組數(shù)據(jù) cut計算:找出data中的最大值最小值,之差除以4,得出區(qū)間值,然后以這個區(qū)間值分四份

data = np.random.randn(20)

用cut函數(shù)將一組數(shù)據(jù)分割成n份 precision:保留小數(shù)點的有效位數(shù)

result = pd.cut(data,4,precision=2)
pd.value_counts(result)

data = np.random.randn(1000)

根據(jù)分位數(shù)差的百分比分割

result=pd.qcut(data,[0,0.1,0.5,0.9,1.0])
pd.value_counts(result)

如果分為數(shù)的差值的和小于1的情況 分割的結(jié)果,安裝分位數(shù)差之和計算

result = pd.qcut(data,[0,0.1,0.3,0.75])
pd.value_counts(result)

series.str.contains

http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html

07、pandas高級應(yīng)用–數(shù)據(jù)的過濾和篩選

data = np.random.randn(1000,4)
df = DataFrame(data)

np.random.seed(num) #num是生成隨機數(shù)的種子

np.random.randn() ##默認生成隨機數(shù)的種子數(shù)是當前時間的時間戳

#定義一個種子數(shù)
np.random.seed(33)
np.random.rand()

np.random.seed(12345)
data = DataFrame(np.random.randn(1000,4))
data

簡單的數(shù)據(jù)統(tǒng)計信息

data.describe()

獲取數(shù)據(jù)的第四列

col = data[3]

篩選出絕對值大于3的數(shù) #對series 直接飲用 np的數(shù)學函數(shù),用中括號來放置條件

col[np.abs(col)>3]

查找出數(shù)據(jù)集中有任意某一列的值出現(xiàn)大于3的行數(shù)據(jù)

data[(np.abs(data)>3).any(1)] #對所有列進行處理

將所有絕對值大于3的正數(shù)設(shè)置為3,絕對值大于3的負數(shù)設(shè)置為-3

獲取數(shù)據(jù)的符號

data[np.abs(data)>3] = np.sign(data)*3 #取符號
data.describe()

08、pandas高級應(yīng)用–讀寫文件數(shù)據(jù)

import sys

pandas讀取csv文件

data = pd.read_csv(‘data/ex1.csv’)
data

讀取的csv文件沒有標題,默認分配表頭索引

pd.read_csv(‘data/ex2.csv’,header=None)

自定義添加標題

pd.read_csv(‘data/ex2.csv’,names=[‘a(chǎn)’,‘b’,‘c’,‘e’,‘name’])

指定行索引

pd.read_csv(‘data/ex2.csv’,names=[‘a(chǎn)’,‘b’,‘c’,‘e’,‘name’],index_col=‘name’) #不是很懂

將讀取的數(shù)據(jù)進行層次化索引

pd.read_csv(‘data/csv_mindex.csv’,index_col=[‘key1’,‘key2’])

通過skiprows參數(shù)指定需要跳過的行索引

pd.read_csv(‘data/ex4.csv’,skiprows=[0,2,3])

加載存在NaN值缺值數(shù)據(jù),把na_values對應(yīng)的值替換為NaN

pd.read_csv(‘data/ex5.csv’,na_values=3)

把數(shù)據(jù)集中的NAN值替換

data.to_csv(sys.stdout,na_rep=[‘NULL’])

只寫入數(shù)據(jù),不寫入行和列的索引

data.to_csv(sys.stdout,index=False,header=False)
data.to_csv(‘data/aa.csv’,index=False,header=False)

通過columns來指定寫入文件中的列

data.to_csv(sys.stdout,index=False,columns=[‘a(chǎn)’,‘c’,‘message’])

09、pandas高級應(yīng)用–數(shù)據(jù)的聚合及分組計算

df = DataFrame({“key”:[‘a(chǎn)’,‘a(chǎn)’,‘b’,‘b’,‘a(chǎn)’],
“key2”:[‘one’,‘two’,‘one’,‘two’,‘one’],
“data1”:np.random.randn(5),
“data2”:np.random.randn(5)})
df

選取data1數(shù)據(jù)列按照key1進行分組

groupd = df[“data1”].groupby(df[‘key’]) #除了可以按列分組,也可以按行分組

調(diào)用已經(jīng)分組好的數(shù)據(jù)中一些方法,即可得出相應(yīng)的統(tǒng)計結(jié)果

獲取分組中每一組數(shù)據(jù)的平均值

groupd.mean()

根據(jù)key和key2兩個列數(shù)據(jù)進行分組

grouped = df[‘data1’].groupby([df[‘key’],df[‘key2’]])

求平均

grouped.mean()

獲取分組后每一組中相應(yīng)元素出現(xiàn)的次數(shù)

df.index
df.groupby([df[‘key’],df[‘key2’]]).size() #或 df.groupby([‘key’,‘key2’]).size() #按行索引分組

for in 循環(huán)輸出分組的結(jié)果

for name,group in df.groupby(“key”):
print(name)
print(group)

將groupby 分類結(jié)果轉(zhuǎn)化成字典

pices = dict(list(df.groupby(‘key’))) #list的時候以逗號分隔key和values,dict 以分號代替逗號
pices[‘b’]

按照列的數(shù)據(jù)類型分組

group = df.groupby(df.dtypes,axis=1)
dict(list(group))
group.size()

選擇分類數(shù)據(jù)中的一個或一組

方法一: 生成的數(shù)據(jù)類型是DataFrame

df.groupby([‘key’,‘key2’])[[‘data2’]].mean()

方法二: 生成的類型是series

df[‘data2’].groupby([df[‘key’],df[‘key2’]]).mean() #series 的groupby 和 dataframe 的groupby 是不一樣的

方法三:

df.groupby([‘key’,‘key2’])[‘data2’].mean()

通過字典或series進行分組

people = DataFrame(np.random.randn(5,5),columns=list(‘a(chǎn)bcde’),index=[‘Joe’,‘Stenve’,‘Wes’,‘Jim’,‘Travis’])
people

創(chuàng)建一個將列名進行映射的字典

mapping = {‘a(chǎn)’:‘red’,‘b’:‘red’,‘c’:‘blue’,‘d’:‘blue’,‘e’:‘red’,‘f’:‘orange’}
by_columns = people.groupby(mapping,axis=1) #相當于對列進行分組
gp=dict(list(by_columns)) #分組之后結(jié)果展示
gp[‘blue’]
by_columns.sum() #橫向相加

將mapping轉(zhuǎn)化成Series

seriesMap = Series(mapping)

people.groupby(seriesMap,axis=1).count() #即是不是這個dataframe的列也是可以作為分組的 #對列的數(shù)目進行統(tǒng)計 對每個行索引來說

分組后常用的計算方法

dict_obj = {‘key1’ : [‘a(chǎn)’, ‘b’, ‘a(chǎn)’, ‘b’, ‘a(chǎn)’, ‘b’, ‘a(chǎn)’, ‘a(chǎn)’],
‘key2’ : [‘one’, ‘one’, ‘two’, ‘three’, ‘two’, ‘two’, ‘one’, ‘three’],
‘data1’: np.random.randint(1,10, 8),
‘data2’: np.random.randint(1,10, 8)}
df = DataFrame(dict_obj)

按照key1進行分組求和

df.groupby(‘key1’).sum()
df[[‘data1’]].groupby(df[‘key1’]).sum()

求最大值

df.groupby(‘key1’).max()

df.groupby(‘key1’).describe()

第一種方法

定義一個函數(shù),求獲得DataFrame中某一列數(shù)據(jù)的最大值和最小值之差

def peak_range(df):
print(type(df))
return df.max()-df.min()

df.groupby(‘key1’).agg(peak_range) #分組之后對每列進行函數(shù)處理

用匿名函數(shù)的方式

第二種方法

df.groupby(‘key1’).agg(lambda df: df.max()-df.min())

使用agg對分組后的數(shù)據(jù)調(diào)用多個聚合函數(shù)

df.groupby(‘key1’).agg([‘mean’,‘sum’,‘count’,‘min’,‘std’,peak_range]) # 帶引號的參數(shù)是內(nèi)置聚合函數(shù)

df.groupby(‘key1’).agg([‘mean’,‘sum’,‘count’,‘min’,‘std’,(‘ptp’,peak_range)]) #peak_range 給peak_range起一個別名,叫ptp #起別名

使用字典實現(xiàn)數(shù)據(jù)集的每列作用不同的聚合函數(shù)

dict_mapping = {‘data1’:‘mean’,‘data2’:‘sum’}
df.groupby(‘key1’).agg(dict_mapping) #agg 傳入函數(shù) 對每列進行不同的操作

以"沒有索引形式"返回聚合函數(shù)的計算結(jié)果

df = pd.DataFrame(data={‘books’:[‘bk1’,‘bk1’,‘bk1’,‘bk2’,‘bk2’,‘bk3’], ‘price’: [12,12,12,15,15,17]})

將分組之后的books列作為索引

df.groupby(“books”,as_index=True).sum() #默認對剩下的price 進行處理

不讓分組之后的books列作為索引

df.groupby(“books”,as_index=False).sum()

tips=pd.read_csv(path+’/input/pandasData/tips.csv’,encoding=‘gbk’)

10、pandas高級應(yīng)用–分組計算apply

為tips數(shù)據(jù)集添加新的一列,作為客戶給的小費占消費總額的百分比

tips[‘tip_pct’] = tips[‘tip’]/tips[‘total_bill’]

定義函數(shù),篩選出小費占比最大的前五條數(shù)據(jù)

def top(df,n=5,columns=‘tip_pct’):
return df.sort_values(by=columns)[-n:]
top(tips,n=6)

#對數(shù)據(jù)集按抽煙進行分組
group = tips.groupby(‘smoker’)

group

使用apply方法分別求出抽煙和不抽煙的客戶中的消費占比排在前五客戶

group.apply(top) #直接對分組結(jié)果進行應(yīng)用函數(shù) 相當于對兩類都進行了處理

顯示抽煙和不抽煙客戶的數(shù)量

group.size()
group.count()

為apply中使用的函數(shù)傳參

tips.groupby([‘smoker’,‘day’],group_keys=False).apply(top,columns=‘total_bill’,n=2) #前面是函數(shù),后面是參數(shù)
#不顯示key
frame = pd.DataFrame({‘data1’: np.random.randn(1000),
‘data2’: np.random.randn(1000)})

result = pd.cut(frame.data1,4) #每個值對應(yīng)一個區(qū)間
pd.value_counts(result)

定義一個函數(shù),求data1數(shù)據(jù)列各項參數(shù)計算

def get_stats(group):
return { ‘min’: group.min(), ‘max’: group.max(),
‘count’:group.count(), ‘mean’: group.mean() }
grouped = frame.data2.groupby(result)

dict(list(grouped))

grouped.apply(get_stats).unstack()

加權(quán)平均和相關(guān)系數(shù)

df = pd.DataFrame({‘category’: [‘a(chǎn)’, ‘a(chǎn)’, ‘a(chǎn)’, ‘a(chǎn)’, ‘b’, ‘b’, ‘b’,‘b’],
‘data’: np.random.randn(8), ‘weights’: np.random.rand(8)})
grouped = df.groupby(‘category’)
grouped.size()

Python數(shù)據(jù)處理進階——pandas

https://www.cnblogs.com/llhy1178/p/6762459.html

df = DataFrame(np.random.randn(4,3), columns= list(“bde”),
index= [“Utah”, “Ohio”, “Texas”, “Oregon”])

print np.abs(df)

將函數(shù)應(yīng)用到各列或行所形成的一維數(shù)組上。

f = lambda x : x.max() - x.min()

每一列的最大值減最小值

print (df.apply(f, axis=0))

每一行的最大值減最小值

print (df.apply(f, axis=1))

返回值由多個值組成的Series

返回值由多個值組成的Series

def f(x):
return Series([x.min(), x.max()], index=[“min”,“max”]) #對每列進行處理
print (df.apply(f)) #默認是對列進行操作

保留兩位小數(shù)點

format = lambda x : “%.2f” % x
print (df.applymap(format)) #apply對series和對整個dataframe,applymap 對整個dataframe,map對series
print (df[“e”].map(format))

通過建立函數(shù)可以實現(xiàn)對數(shù)據(jù)庫所有元素的修改操作
對dataframe的整體操作 所有元素操作

總的來說就是apply()是一種讓函數(shù)作用于列或者行操作,applymap()是一種讓函數(shù)作用于DataFrame每一個元素的操作,而map是一種讓函數(shù)作用于Series每一個元素的操作

排序和排名

obj = Series(np.arange(4.), index=[“b”,“a”,“d”,“c”])

print obj.sort_index()

frame = DataFrame(np.arange(8).reshape((2,4)),index=[“three”,“one”],
columns=[“d”,‘a(chǎn)’,‘b’,‘c’])

按照索引的行進行排序

print (frame.sort_index(axis=1))

按照索引的列進行排序

print frame.sort_index(axis=0)

按照值的列進行排序(必須傳入一個列的索引且只能排列一組)

frame.sort_values(‘b’, axis=0, ascending=False)

按照值的行進行排序(必須傳入一個行的索引且只能排列一組)

frame.sort_values(“one”, axis=1, ascending=False)

根據(jù)多個列進行排序

frame.sort_index(by=[“a”,“b”])

排名

obj1 = Series([7,-5,7,4,2,0,4])
obj1.rank()

加減乘除 add代表加,sub代表減, div代表除法, mul代表乘法

df1 = DataFrame(np.arange(12).reshape((3,4)), columns=list(“abcd”))
df2 = DataFrame(np.arange(20).reshape((4,5)), columns=list(“abcde”))

df1 + df2 #找不到匹配的位置直接為空

將缺失值用0代替

df1.add(df2, fill_value=0) #找不到匹配的位置用單獨一方的值替代

再進行重新索引時,也可以指定一個填充值

df1.reindex(columns=df2.columns, fill_value=0)

data = {“state”: [“Ohio”,“Ohio”,“Ohio”,“Nevada”,“Nevada”],
“year” : [2000, 2001, 2002, 2001, 2002],
“pop” : [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)

frame

矩陣的橫坐標

frame.columns

矩陣的縱坐標

print frame.index

獲取列通過類似字典標記的方式或?qū)傩缘姆绞?#xff0c;可以將DataFrame的列獲取為一個Series:

print frame[“state”]

print frame.year

獲取行也通過類似字典標記的方式或?qū)傩缘姆绞?#xff0c;比如用索引字段ix

print frame.ix[3]

精準匹配

val = Series([-1.2, -1.5, -1.7], index=[“two”, “four”, “five”])
frame.index = Series([‘one’, ‘two’, ‘three’, ‘four’, ‘five’])
frame.debt = val #debt 是啥東東

print frame

為不存在的列賦值存在列中的某個值會創(chuàng)建出一個布爾列。關(guān)鍵字del用于刪除列。

frame[“eastern”] = frame.state == “Ohio”

del frame[“eastern”] # 只能這樣表示 刪除列

嵌套字典

pop = { “Nevada” : {2001 : 2.4, 2002 : 2.9},
“Ohio” : {2000 : 1.5, 2001 : 1.7, 2002 : 3.6}
}

傳給DataFrame,它會被解釋為:外層字典的鍵作為列,內(nèi)層鍵則作為行索引

frame2 = DataFrame(pop)

對該結(jié)果進行轉(zhuǎn)置

frame2.T

內(nèi)層字典的鍵會被合并、排序以形成最終的索引。

frame3 = DataFrame(pop, index=[2001, 2002, 2003])
frame3.index.name = “year”; frame3.columns.name = “state” #索引和列只有一個名字

重新索引

obj = Series([4.5, 7.2, -5.3, 3.6], index=[“d”, “b”, “a”, “c”])

reindex將會根據(jù)新索引進行重排。

obj2 = obj.reindex([“a”, “b”, “c”, “d”, “e”])

print obj2

將缺失值用0代替

obj2 = obj.reindex([“a”, “b”, “c”, “d”, “e”], fill_value= 0)

print obj2

插值處理–Series

obj3 = Series([“blue”, “purple”, “yellow”], index=[0,2,4])

前向填充ffill或pad

obj3.reindex(range(6), method=“ffill”)

print a

后向填充bfill或backfill

b = obj3.reindex(range(6), method=“bfill”)

print b

插值處理–DataFrame

import numpy as np
f = DataFrame(np.arange(9).reshape((3,3)), index=[“a”,“c”,“d”],
columns=[“Ohio”, “Texas”, “California”])

改變行的索引

f2 = f.reindex([“a”,“b”,“c”,“d”], fill_value=9)

print f2

改變列的索引

col = [“Texas”, “Utah”, “California”]
f3 = f.reindex(columns=col)

print f3

同時改變列和行的索引 不成功

f4 = f.reindex([“a”,“b”,“c”,“d”], method=“ffill”,
columns=[“Texas”, “Utah”, “California”])

print f4

丟棄指定軸上的項–Series

mys = Series(np.arange(5.), index=[“a”,“b”,“c”,“d”,“e”])

print mys

drop()刪除某個索引以及對應(yīng)的值

mys_new = mys.drop(“c”)

print mys_new

mys_new1 = mys.drop([“c”,“e”])

print mys_new1

丟棄指定軸上的項–DataFrame

data = DataFrame(np.arange(16).reshape((4,4)),
index=[“Ohio”, “Colorado”, “Utah”, “New York”],
columns=[“one”, “two”, “three”, “four”])

刪除某行軸上的值

data1 = data.drop([“Ohio”,“Utah”], axis=0) # axis=0代表行

print data1

刪除某列軸上的值

data2 = data.drop([“one”,“three”], axis=1) # axis=1代表列

print data2

obj = Series(range(5), index=[‘a(chǎn)’, ‘a(chǎn)’, ‘b’, ‘b’, ‘c’])

使用is_unique屬性可以知道他的值是否是唯一的

obj.index.is_unique

obj[‘a(chǎn)’]

df = DataFrame(np.random.randn(4, 3), index=[‘a(chǎn)’, ‘b’, ‘a(chǎn)’, ‘b’])
df.ix[“b”, 1]
df[1]

pandas中的索引高級處理:

索引、選取和過濾–Series

obj = Series(np.arange(4), index=[“a”,“b”,“c”,“d”])

print obj[“b”]

print obj[1]

print obj[2:4]

print obj[[“b”,“a”,“d”]]

print obj[[1,3]]

print obj[obj < 2]

利用標簽的切片運算與普通的python切片運算不同,其末端是包含的

print obj[“b”:“c”]

obj[“b”:“c”] = 5

print obj

結(jié)束

總結(jié)

以上是生活随笔為你收集整理的dataframe,python,numpy 问题索引1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。