2020国产成人精品视频,性做久久久久久久久,亚洲国产成人久久综合一区,亚洲影院天堂中文av色

分享

python-對(duì)Pandas DataFrame使用邏輯索引或布爾索引的正確語(yǔ)法是什么?

 印度阿三17 2019-10-27

我要使用邏輯索引來(lái)修改Pandas DataFrame(版本0.15.2)中的值,如本post所述.我一直收到以下警告:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the the caveats in the documentation: http://pandas./pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self.obj[item_labels[indexer[info_axis]]] = value

這是一個(gè)示例進(jìn)行演示.

import pandas as pd
import numpy as np
df = pd.DataFrame({'A':[9,10]*6,
                   'B':range(23,35),
                   'C':range(-6,6)})

print df
     A   B  C
0    9  23 -6
1   10  24 -5
2    9  25 -4
3   10  26 -3
4    9  27 -2
5   10  28 -1
6    9  29  0
7   10  30  1
8    9  31  2
9   10  32  3
10   9  33  4
11  10  34  5

使用邏輯索引更改值的正確方法是什么?假設(shè)我要從B列中所有> 30,為什么不首選以下內(nèi)容?我意識(shí)到這是鏈?zhǔn)阶鳂I(yè),不鼓勵(lì)使用.在我實(shí)際上使用的代碼中,它確實(shí)完成了我想要的操作(它不是進(jìn)行復(fù)制,而是實(shí)際上在編輯原始DataFrame),但仍顯示警告:

df['B-type'] = 'B'                  # create column with dummy values
df['B-type'][df['B'] > 30] = 'BI'   # populate the column with real values for BI type
df['B-type'][df['B'] <= 30] = 'BII' # populate the column with real values for BII type
print df
     A   B  C B-type
0    9  23 -6    BII
1   10  24 -5    BII
2    9  25 -4    BII
3   10  26 -3    BII
4    9  27 -2    BII
5   10  28 -1    BII
6    9  29  0    BII
7   10  30  1    BII
8    9  31  2     BI
9   10  32  3     BI
10   9  33  4     BI
11  10  34  5     BI

目前尚不清楚為什么這是“錯(cuò)誤的”,但仍然可以正常工作.

解決方法:

一種方法是使用如下所示的.loc

df.loc[df['B'] > 30,'B'] = df.loc[df['B'] > 30,'B'] - 10

演示-

In [9]: df = pd.DataFrame({'A':[9,10]*6,
   ...:                    'B':range(23,35),
   ...:                    'C':range(-6,6)})

In [10]:

In [10]: df
Out[10]:
     A   B  C
0    9  23 -6
1   10  24 -5
2    9  25 -4
3   10  26 -3
4    9  27 -2
5   10  28 -1
6    9  29  0
7   10  30  1
8    9  31  2
9   10  32  3
10   9  33  4
11  10  34  5

In [11]: df.loc[df['B'] > 30,'B'] = df.loc[df['B'] > 30,'B'] - 10

In [12]: df
Out[12]:
     A   B  C
0    9  23 -6
1   10  24 -5
2    9  25 -4
3   10  26 -3
4    9  27 -2
5   10  28 -1
6    9  29  0
7   10  30  1
8    9  21  2
9   10  22  3
10   9  23  4
11  10  24  5

或者,如評(píng)論中所述,您還可以使用上述擴(kuò)展作業(yè)版本-

df.loc[df['B'] > 30,'B'] -= 10
來(lái)源:https://www./content-1-528351.html

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多