日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

python-對Pandas DataFrame使用邏輯索引或布爾索引的正確語法是什么?

 印度阿三17 2019-10-27

我要使用邏輯索引來修改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

這是一個示例進行演示.

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)容?我意識到這是鏈?zhǔn)阶鳂I(yè),不鼓勵使用.在我實際上使用的代碼中,它確實完成了我想要的操作(它不是進行復(fù)制,而是實際上在編輯原始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

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

解決方法:

一種方法是使用如下所示的.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

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

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

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

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多