简体   繁体   English

迭代并更改以熊猫为单位的行的值(错误“ [index]中[Int64Index([10],dtype ='int64')]都不存在”)

[英]Iterating and changing value of the row in pandas ( Error “None of [Int64Index([10], dtype='int64')] are in the [index]” )

import pandas as pd

inp = [{'c1':10, '10':100, '11':100, '12':100},   
       {'c1':11,'10':110, '11':100, '12':100},  
       {'c1':12,'10':120, '11':100, '12':100}] .   

df = pd.DataFrame(inp)

     10      11      12     c1
0   100     100     100     10   
1   110     100     100     11   
2   120     100     100     12   

Expected Output ::

     10      11      12     c1
0   XX      100     100     10   
1   110     XX      100     11   
2   120     100     XX      12    

Basically I want to iterate each row and want to select the value of c1 column (example - in first iteration I will get value 10) and than by taking that value of c1 I want to change value of the raw [row[''c1]] to XX (example - value which we got 10 , now I want to change the value of raw['10'] to XX 基本上,我想遍历每一行并希望选择c1列的值(示例-在第一次迭代中,我将获得值10),而不是通过获取c1的值,我想更改原始[row [''c1 ]]改为XX(示例-我们得到10的值,现在我想将raw ['10']的值更改为XX

I tried: 我试过了:

for row in df.itertuples(index=True, name='Pandas'):  
    variable=getattr(row, "c1")  
    df.loc[{variable}]=1   

    Error what I Am getting is:
---------------------------------------------------------------------------

    KeyError                                  Traceback (most recent call last)
    <ipython-input-226-e67900963f1d> in <module>
          7 for row in df.itertuples(index=True, name='Pandas'):
          8     variable=getattr(row, "c1")
    ----> 9     df.loc[{variable}]=1
         10 
         11 df

    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in __setitem__(self, key, value)
        187         else:
        188             key = com.apply_if_callable(key, self.obj)
    --> 189         indexer = self._get_setitem_indexer(key)
        190         self._setitem_with_indexer(indexer, value)
        191 

    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _get_setitem_indexer(self, key)
        173 
        174         try:
    --> 175             return self._convert_to_indexer(key, is_setter=True)
        176         except TypeError as e:
        177 

    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter, raise_missing)
       1352                 kwargs = {'raise_missing': True if is_setter else
       1353                           raise_missing}
    -> 1354                 return self._get_listlike_indexer(obj, axis, **kwargs)[1]
       1355         else:
       1356             try:

    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing)
       1159         self._validate_read_indexer(keyarr, indexer,
       1160                                     o._get_axis_number(axis),
    -> 1161                                     raise_missing=raise_missing)
       1162         return keyarr, indexer
       1163 

    /usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)
       1244                 raise KeyError(
       1245                     u"None of [{key}] are in the [{axis}]".format(
    -> 1246                         key=key, axis=self.obj._get_axis_name(axis)))
       1247 
       1248             # We (temporarily) allow for some missing keys with .loc, except in

    KeyError: "None of [Int64Index([10], dtype='int64')] are in the [index]"

You can do this: 你可以这样做:

res = df.copy()

for i in df.iterrows():
    res.loc[i[0], str(i[1]['c1'])] = 'xx'

res

    10      11      12  c1
0   xx     100     100  10
1   110     xx     100  11
2   120     100     xx  12

Looping in pandas is not recommended, because slow, but if need it: 不建议在熊猫中循环播放,因为速度较慢,但​​如果需要的话:

for row in df.itertuples(index=True, name='Pandas'):  
    variable=getattr(row, "c1")  
    df.loc[row.Index, str(variable)]= 'XX'  

print (df)
    10   11   12  c1
0   XX  100  100  10
1  110   XX  100  11
2  120  100   XX  12

You can also loop by dict: 您也可以按字典循环:

for k, v in df['c1'].to_dict().items():
    df.loc[k, str(v)] = 'XX'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 关键错误:[Int64Index([…]dtype='int64')] 均不在 [columns] 中 - Key Error: None of [Int64Index([…]dtype='int64')] are in the [columns] 关键错误:[Int64Index…] dtype='int64] 均不在 [columns] 中 - Key Error: None of [Int64Index…] dtype='int64] are in the [columns] Sklearn 错误:[Int64Index([2, 3], dtype=&#39;int64&#39;)] 均不在 [columns] 中 - Sklearn error: None of [Int64Index([2, 3], dtype='int64')] are in the [columns] [Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64', name='index')] 中没有一个在 [index] - None of [Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64', name='index')] are in the [index] KeyError: &quot;[Int64Index([ 12313,\\n, 34534],\\n dtype=&#39;int64&#39;, leng - KeyError: "None of [Int64Index([ 12313,\n , 34534],\n dtype='int64', leng 读取 CSV &amp; Columns - KeyError: “[Int64Index([0, 1, 2, 3], dtype='int64')] 都在 [columns] 中” - Reading CSV & Columns - KeyError: “None of [Int64Index([0, 1, 2, 3], dtype='int64')] are in the [columns]” KeyError:“[Int64Index dtype=&#39;int64&#39;, length=9313)] 都不在 [columns]” - KeyError: "None of [Int64Index dtype='int64', length=9313)] are in the [columns]" Receiving KeyError: “[Int64Index([ ... dtype=&#39;int64&#39;, length=1323)] 都不在 [columns]” - Receiving KeyError: "None of [Int64Index([ ... dtype='int64', length=1323)] are in the [columns]" Python Mlens Ensemble:KeyError:“[Int64Index([... dtype='int64', length=105)] 均不在 [columns] 中” - Python Mlens Ensemble: KeyError: "None of [Int64Index([... dtype='int64', length=105)] are in the [columns]" 将Int64Index更改为Index,将dtype = int64更改为dtype = object - Change Int64Index to Index and dtype=int64 to dtype=object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM