python corrwith_python – pandas.DataFrame corrwith()方法
我最近開(kāi)始和熊貓一起工作.任何人都可以用Series和DataFrame來(lái)解釋函數(shù).corrwith()的行為差異嗎?
假設(shè)我有一個(gè)DataFrame:
frame = pd.DataFrame(data={'a':[1,2,3], 'b':[-1,-2,-3], 'c':[10, -10, 10]})
我想要計(jì)算特征’a’和所有其他特征之間的相關(guān)性.
我可以通過(guò)以下方式完成:
frame.drop(labels='a', axis=1).corrwith(frame['a'])
結(jié)果將是:
b -1.0
c 0.0
但非常相似的代碼:
frame.drop(labels='a', axis=1).corrwith(frame[['a']])
生成絕對(duì)不同且不可接受的表格:
a NaN
b NaN
c NaN
所以,我的問(wèn)題是:為什么在DataFrame作為第二個(gè)參數(shù)的情況下,我們得到如此奇怪的輸出?
解決方法:
我認(rèn)為你在尋找什么:
假設(shè)您的框架是:
frame = pd.DataFrame(np.random.rand(10, 6), columns=['cost', 'amount', 'day', 'month', 'is_sale', 'hour'])
您希望“費(fèi)用”和“金額”列與每個(gè)組合中的所有其他列相關(guān)聯(lián).
focus_cols = ['cost', 'amount']
frame.corr().filter(focus_cols).drop(focus_cols)
回答你的問(wèn)題:
Compute pairwise
correlation between rows or columns of two DataFrame objects.
Parameters:
other : DataFrame
axis : {0 or ‘index’, 1 or ‘columns’},
default 0 0 or ‘index’ to compute column-wise, 1 or ‘columns’ for row-wise drop : boolean, default False Drop missing indices from
result, default returns union of all Returns: correls : Series
corrwith的行為類(lèi)似于add,sub,mul,div,因?yàn)樗M业揭粋€(gè)DataFrame或一個(gè)正在傳遞的系列,盡管文檔只說(shuō)DataFrame.
當(dāng)其他是系列時(shí),它播放該系列并沿軸指定的軸匹配,默認(rèn)為0.這就是以下工作的原因:
frame.drop(labels='a', axis=1).corrwith(frame.a)
b -1.0
c 0.0
dtype: float64
當(dāng)other是DataFrame時(shí),它將匹配軸指定的軸并關(guān)聯(lián)由另一個(gè)軸標(biāo)識(shí)的每個(gè)對(duì).如果我們這樣做:
frame.drop('a', axis=1).corrwith(frame.drop('b', axis=1))
a NaN
b NaN
c 1.0
dtype: float64
只有c是共同的,只有c計(jì)算了它的相關(guān)性.
在您指定的情況下:
frame.drop(labels='a', axis=1).corrwith(frame[['a']])
frame [[‘a(chǎn)’]]是一個(gè)DataFrame,因?yàn)閇[‘a(chǎn)’]]并且現(xiàn)在由DataFrame規(guī)則播放,其中的列必須與其相關(guān)的列匹配.但是你明確地從第一幀中刪除了一個(gè)然后與一個(gè)只有一個(gè)的數(shù)據(jù)幀相關(guān)聯(lián).結(jié)果是每列的NaN.
標(biāo)簽:python,pandas,dataframe
來(lái)源: https://codeday.me/bug/20191008/1870198.html
總結(jié)
以上是生活随笔為你收集整理的python corrwith_python – pandas.DataFrame corrwith()方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 段永平到底有多少钱 看看他的商界历程就知
- 下一篇: vue重启node_【ts】vue-ty