pandas如何新增一列,對相同的行賦同乙個值?

時間 2021-05-10 02:41:12

1樓:peter

利益相關,我是pandas 貢獻者。

import

pandas

aspd

import

numpy

asnp

from

functools

import

lru_cache

from

itertools

import

permutationsdf=

pd.DataFrame

(data

=permutations

(range(0

,3)),columns

=list

('abc'

))df=pd

.concat

([df]*

3).reset_index

(drop

=True

)資料是這樣

array([[0, 1, 2],

[0, 2, 1],

[1, 0, 2],

[1, 2, 0],

[2, 0, 1],

[2, 1, 0],

[0, 1, 2],

[0, 2, 1],

[1, 0, 2],

[1, 2, 0],

[2, 0, 1],

[2, 1, 0],

[0, 1, 2],

[0, 2, 1],

[1, 0, 2],

[1, 2, 0],

[2, 0, 1],

[2, 1, 0]])

我的方法,使用代cache的累加。cache意義在於遇到重複值,直接從快取中讀取上次的結果

from functools import lru_cache

counter=0

@lru_cache(maxsize=100) #快取大小根據情況調整,也可以用另外乙個memoize裝飾器,就不用了

def rank1(x):

global counter

if counter == 0counter +=1

return 1

elsecounter += 1

return counter

#測速度

%%timeit

global counter

counter = 0 #手動將global技術設定為0 因為timeit會跑多次

rank1.cache_clear() #快取清空, 因為timeit會跑1000個loop,不使用上次的結果

結果是925 s ± 11.4 s per loop (mean ± std. dev. of 7 runs, 1000 loops each)

factorize方法

groupby 後merge方法

# 用 groupby 計算出每一行對應的唯一值,這裡直接用自增 index 行

col_names=[

'a',

'b',

'c']

df_key=df

.groupby

(col_names).

size().

reset_index().

drop

(columns=[

0]).reset_index

()df_new=pd

.merge(df

,df_key

,how

='left'

)5.34 ms ± 106 s per loop (mean ± std. dev. of 7 runs, 100 loops each)

我的環境配置如下

INSTALLED VERSIONS

commitd9fff2792bf16178d4e450fe7384244e50635733

python3.7.7.final.0

python-bits : 64

OSLinux

OS-release : 3.10.0-1062.el7.x86_64

Version1 SMP Wed Aug 7 18:08:02 UTC 2019

machinex86_64

processorx86_64

byteorderlittle

LC_ALLNone

LANGzh_CN.UTF-8

LOCALEzh_CN.UTF-8

pandas1.1.0

numpy1.18.5

2樓:

有pd為啥不用np現成的

假如10行,想負值為100

df['new']=np.ones(10)*100df

3樓:duangsuse

有正確答案了,也來獻個醜。是生成一列這樣的:

const

cycle=[

1,2,

3,4,

5];function

nextIn(xs

,x)function

*genCol

(rows)}

[...

genCol

([[1,2

,3,4

,5],[

5,4,

3,2,

1],[1

,2,3

,4,5

]])]

//[1,2,1]

直接換成 Python,下面的大佬弄的太好了我不敢看(QAQ)……cycle

=list

(range(1

,5+1

))def

nextIn(xs

,x):return

xs[(xs.

index(x

)+1)

%len(xs

)]def

genCol

(rows

):for

rowin

rows

:yield

nextIn

(cycle

,row[-

1])list

(genCol

([range(1

,6),range(5

,0,-

1),range(1

,6)]))

4樓:

import

pandas

aspddf=

pd.DataFrame([[

1,2,

3,4,

5],[1

,2,3

,4,5

],[5,

4,3,

2,1],

[5,4

,3,2

,1],[

5,4,

3,2,

3]],columns

=list

('abcde'

))new_col=

foridx,i

indf

.iterrows

():if

list(df

.loc

[idx,df

.columns

])==[1

,2,3

,4,5

]:new_col.(

1)elif

list(df

.loc

[idx,df

.columns

])==[5

,4,3

,2,1

]:new_col.(

2)else

:new_col.(

None)df

.loc

[:,'new_col']=

new_col

5樓:林君天

思路是一樣的,先在原資料中計算每一行對應的唯一值,然後拼接。這裡提供乙個效率較高的做法。

import

pandas

aspd

lst=[[

1,2,

3,4,

5],[1

,2,3

,4,5

],[5,

4,3,

2,1],

[5,4

,3,2

,1],[

1,2,

2,2,

2]]col_names

=list

("abcde")df

=pd.DataFrame

(lst

,columns

=col_names

)# 用 groupby 計算出每一行對應的唯一值,這裡直接用自增 index 行

df_key=df

.groupby

(col_names).

size().

reset_index().

drop

(columns=[

0]).reset_index

()indexab

cde0

0122

2211

1234

5225

4321

# 用 merge 直接匹配出每一行的數值df_new=pd

.merge(df

,df_key

,how

='left')a

bcde

index01

2345

1112

3451

2543

2123

5432

1241

22220

6樓:

先把每行的數字轉換成字串連起來,去個重,作為key,做乙個字典,反過來用來替換按行連起來的字串:

import

pandas

aspd

lst=[[

1,2,

3,4,

5],[1

,2,3

,4,5

],[5,

4,3,

2,1],

[5,4

,3,2

,1],[

1,2,

2,2,

2]]df

=pd.DataFrame

(lst

,columns

=list

("abcde"

))unique_lists=df

.astype

(str).

("".join

,axis=1

).unique

()repl_dict

=dict

(zip

(unique_lists

,range(1

,len

(unique_lists)+

1)))df[

'f']=df

.astype

(str).

("".join

,axis=1

).replace

(repl_dict

)結果:

a b c d e f

0 1 2 3 4 5 1

1 1 2 3 4 5 1

2 5 4 3 2 1 2

3 5 4 3 2 1 2

4 1 2 2 2 2 3

7樓:肖肖肖肖不敢實名

一種方法是設計乙個作為匹配資訊的key列,然後value_count一下做成字典然後再匹配回去

第二種方法排個序,然後iter_row,按順序做乙個列表

pandas 怎麼根據一列的資料的值的情況判斷來生成另外一列的數值

星空流 其他回答已經很全面了。我再介紹兩種方法。以下面的資料為例。使用np.where 方法,這個方法用起來與if類似,但是是基於numpy的,numpy的特性是一起計算,而if是乙個乙個計算,所以np.where 速度非常快。apl 漲跌 np.where apl 3 0,漲 np.where a...

有兩列速度相同的高速列車載原子鐘,一列向東開,另一列向西開,哪列車上的原子鐘耗時少?

楊昇山 你提的問題在1971年就有人做了實驗 我不能判斷是不是真的做了 就是使用飛機上的原子鐘對相對論效應進行驗證。具體你可以搜尋我寫的 物理鐘的變化不能作為相對論正確的證據 張冠偉 首先我們假設地球不旋轉,同時忽略地球自身公轉等導致的非慣性運動,那麼地面上的人就是天然的慣性系。我們以他的座標為參考...

svm新增一列自身複製的特徵後,作為支撐向量的樣本點會改變嗎?

Zhang Yao 這個問題挺有意思的,有點面試題的感覺,稍微推導了一下,結論如下。太長不看 對於Hard Margin的Linear SVM,支援向量是不變的。還是Hard Margin的情況,加了Kernel的SVM,則要看Kernel的具體形式,大多數情況支援向量也是不變的。對於Soft Ma...