分享

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

使用逻辑索引更改值的正确方法是什么?假设我要从B列中所有> 30,为什么不首选以下内容?我意识到这是链式作业,不鼓励使用.在我实际上使用的代码中,它确实完成了我想要的操作(它不是进行复制,而是实际上在编辑原始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

或者,如评论中所述,您还可以使用上述扩展作业版本-

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约