使用间隔索引在 DataFrame 中设置特定值

让我有一个这样的数据框:


test_df = pd.DataFrame(

        0, 

        index = pd.IntervalIndex.from_breaks([100, 200, 300, 400]),

        columns = ['A', 'B', 'C']

)

所以它会给我们这个:


            A   B   C

(100, 200]  0   0   0

(200, 300]  0   0   0

(300, 400]  0   0   0

现在,假设我想在给定的间隔中更改特定值,在我的数据帧中的某些间隔中具有整数值。


我可以用得到的区间值,.loc通过这个weay特定定整数值: test_df.loc[250]。这会给我系列。


但!


第一种情况:


test_df.at[250, 'B']

------

ValueError: At based indexing on an non-integer index can only have non-integer indexers

为什么250在这种情况下我不能使用整数值?它适用于.loc.



第二种情况:


test_df.loc[250, 'B']

------

'pandas._libs.interval.IntervalTree' object has no attribute 'get_value'

没有属性get_value?那么我怎样才能获得价值呢?我可以只通过系列来做,通过.loc财产获得吗?



第三种情况:


test_df.at[250, 'B'] = 10

------

'pandas._libs.interval.IntervalTree' object has no attribute 'set_value'

主要问题

我应该如何在数据框中设置特定值?


手掌心
浏览 367回答 3
3回答

至尊宝的传说

.loc 如果您为它提供第二组标签的列表,则当前有效:test_df.loc[250, ['B']]#B    0#Name: (200, 300], dtype: int64test_df.loc[250:400, ['B', 'C']]#            B  C#(200, 300]  0  0#(300, 400]  0  0test_df.loc[250, ['B']] = 10print(test_df)#            A   B  C#(100, 200]  0   0  0#(200, 300]  0  10  0#(300, 400]  0   0  0

UYOU

请注意, 的行为loc已得到修复,并将出现在即将发布的 0.24.0 版本中:In [1]: import pandas as pd; pd.__version__Out[1]: '0.24.0.dev0+870.g7191af9b4'In [2]: test_df = pd.DataFrame(   ...:         0,   ...:         index = pd.IntervalIndex.from_breaks([100, 200, 300, 400]),   ...:         columns = ['A', 'B', 'C']   ...: )In [3]: test_dfOut[3]:            A  B  C(100, 200]  0  0  0(200, 300]  0  0  0(300, 400]  0  0  0In [4]: test_df.loc[250, 'B']Out[4]: 0In [5]: test_df.loc[250, 'B'] = 100In [6]: test_dfOut[6]:            A    B  C(100, 200]  0    0  0(200, 300]  0  100  0(300, 400]  0    0  0

侃侃无极

test_df.loc[250].at['B'] = whatever但请确保任何与列数据类型相同的类型
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python