简体   繁体   中英

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM