logo
down
shadow

Assign subset of values to pandas dataframe with MultiIndex


Assign subset of values to pandas dataframe with MultiIndex

By : Calm
Date : October 23 2020, 08:10 PM
Any of those help You can simply do df/sums, no need for loop.
Since that you want to assign to a particular part of dataframe you can do it this way. Keep the depth of computed df 1 level higher.
code :
df.loc['A',:] = df.loc['A',:,:].apply(lambda x: x/sums.loc['A','Count'])


Share : facebook icon twitter icon
Pandas : Proper way to set values based on condition for subset of multiindex dataframe

Pandas : Proper way to set values based on condition for subset of multiindex dataframe


By : Tanner Barnes
Date : March 29 2020, 07:55 AM
hop of those help? This is an application of (and one of the main motivations for using MultiIndex slicers), see docs here
code :
In [20]: df = pd.DataFrame({('A','a'): [-1,-1,0,10,12],
                   ('A','b'): [0,1,2,3,-1],
                   ('B','a'): [-20,-10,0,10,20],
                   ('B','b'): [-200,-100,0,100,200]})

In [21]: df
Out[21]: 
    A      B     
    a  b   a    b
0  -1  0 -20 -200
1  -1  1 -10 -100
2   0  2   0    0
3  10  3  10  100
4  12 -1  20  200

In [22]: idx = pd.IndexSlice

In [23]: mask = df.loc[:,idx['A',:]]<0

In [24]: mask
Out[24]: 
       A       
       a      b
0   True  False
1   True  False
2  False  False
3  False  False
4  False   True

In [25]: df[mask] = 0

In [26]: df
Out[26]: 
    A      B     
    a  b   a    b
0   0  0 -20 -200
1   0  1 -10 -100
2   0  2   0    0
3  10  3  10  100
4  12  0  20  200
In [30]: df[df[['A']]<0] = 0

In [31]: df
Out[31]: 
    A      B     
    a  b   a    b
0   0  0 -20 -200
1   0  1 -10 -100
2   0  2   0    0
3  10  3  10  100
4  12  0  20  200
Randomly assign values to subset of rows in pandas dataframe

Randomly assign values to subset of rows in pandas dataframe


By : shan
Date : March 29 2020, 07:55 AM
will be helpful for those in need I am using Python 2.7.11 with Anaconda. , You must determine the size of group 2
code :
g2 = df['group'] == 2
df.loc[g2, 'value'] = np.random.randint(5, size=g2.sum())
print(df)

   group  value
0      1    NaN
1      1    NaN
2      1    NaN
3      2    3.0
4      2    4.0
5      2    2.0
Pandas DataFrame: Assign values from a column to a subset of original dataframe without copying

Pandas DataFrame: Assign values from a column to a subset of original dataframe without copying


By : eeezit soft
Date : March 29 2020, 07:55 AM
like below fixes the issue I want to assign the values of a column in a DataFrame to a subset of another column in the same original DataFrame. Consider the following example: , Option 1 : Use a conditional to match the index i.e
code :
df.loc[df.index==1,'B'] =df.loc[1,'A']
df['B'] = np.where(df['B'].index==1,df['A'],df['B'])
df['B']  = df['B'].where(~(df['B'].index==1),df['A'])
          A         B         C         D str
0 -0.549047 -0.608938 -0.355242  1.362221   a
1  0.298822  0.298822  1.591475  0.146636   a
1 -0.292439 -0.292439  0.425860  0.117091   a
2 -1.715484 -0.343491 -1.448902  1.394756   a
1  0.657651  0.657651 -0.002407  1.317446   a
3 -0.698070 -0.740400 -1.348418 -0.800586   a
4 -1.043036 -0.161858  1.110410  0.275207   a
5  0.050947 -1.424375  0.260261 -1.058468   a
How to check equality between pandas dataframe multiindex subset?

How to check equality between pandas dataframe multiindex subset?


By : user1571838
Date : March 29 2020, 07:55 AM
it helps some times You want to match on multiple column values, some of which are in the index and some of which are not. DataFrame.merge is really what you want.
code :
example.reset_index().merge(example2).set_index(['A', 'B'])
          value1  value2
A   B                   
bar blih       1      23
foo blih      23       1
example.merge(example2, on=['B', 'value1', 'value2']) 
      value1  value2
B                   
blih      23       1
blih       1      23
Pandas, how to dropna values using subset with multiindex dataframe?

Pandas, how to dropna values using subset with multiindex dataframe?


By : user3179664
Date : March 29 2020, 07:55 AM
wish of those help When dealing with a MultiIndex, each column of the MultiIndex can be specified as a tuple:
code :
In [67]: df.dropna(axis=0, how="all", subset=[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')])
Out[67]: 
     1         2       3   
     a    b    a    b  a  b
0  1.0  2.0  3.0  4.0  5  6
1  NaN  NaN  1.0  2.0  3  4
2  NaN  1.0  2.0  3.0  4  5
3  NaN  NaN  5.0  3.0  3  2
In [69]: df.dropna(axis=0, how="all", subset=df.loc[[], [1,2]].columns)
Out[69]: 
     1         2       3   
     a    b    a    b  a  b
0  1.0  2.0  3.0  4.0  5  6
1  NaN  NaN  1.0  2.0  3  4
2  NaN  1.0  2.0  3.0  4  5
3  NaN  NaN  5.0  3.0  3  2
Related Posts Related Posts :
  • Submitting login form with scrapy
  • How do i edit the favicon in the Browsable API in Django REST framework?
  • multiprocessing.Pool.map_async doesn't seem to... do anything at all?
  • Python Selenium: Stale Element Reference Exception Error
  • Datetime conversion - How to extract the inferred format?
  • Import YAML variables automatically?
  • How to create a powershell shortcut for my python file
  • Python's 'set' operator doesn't work with numpy.nan
  • Pass object fields and one2many fields on same method - Odoo v8
  • Select columns based on column name and location in Pandas
  • Standardizing timeseries in Pandas using interpolation
  • How many tweets can be collected?
  • how format specifier taking value while tuple list is passed
  • How to print a numpy array with data type?
  • Timeout child thread for python3
  • How can I regroup a dataframe and accumulate a colume's values?
  • Bulk Insert into SQL Server with Python not working
  • Removing last rows of each group based on condition in a pandas dataframe
  • Why the css file can not be found in Django template?
  • targeting center of mass - scipy / numpy
  • Foursquare - get tips from VENUE_ID
  • Unpack a dictionary to format
  • encoding special characters in python2
  • Replacing integers with NaN results in the entire column becoming float dtype
  • Python 3.6 - BeautifulSoup4, parse table AttributeError: ResultSet object has no attribute 'findAll'
  • Convert panda date list to python list of date strings
  • escape response from Scrapy to parse json
  • How to create a same dropdown menu for different labels?
  • Why are some python variables uppercase whereas others are lowercase?
  • Machine Learning, What are the common techniques for feature engineering and presenting the model?
  • Modify value of a Django form field during clean() and validate again
  • Heroku Django app can't start up -- 'No module named site'
  • Getting list of dates (excluding weekends)
  • Im trying to create the regular expression to include the text and not the href
  • Python file.readline(2) reads first 2 charectars
  • Groupby with handling empty bin in python
  • Modifying Gcode
  • calling a value in a dictionary within a dictionary (reading a json file)
  • Bouncing ball invalid syntax why is that?
  • Python making a counter
  • Python rstrip and split
  • What does the String mean in numpy.r_?
  • How to correctly extend variable __all__ in a __init__.py?
  • Python behaves weird with piped input
  • Python 3 two dimensional list comprehension
  • How to slice image by broadcasting slices? Error: 'only integer scalar arrays can be converted to a scalar index' in pyt
  • (Python Beginner) Need a start on classes
  • IndexError: At least one sheet must be visible
  • How to solve a system of linear equations over the nonnegative integers?
  • Pandas keep the most complete rows
  • "List index out of range" error in Python Memory Match game
  • Numpy: how to use argmax results to get the actual max?
  • Google Cloud Dataflow can't import 'google.cloud.datastore'
  • Calculate pandas DataFrame column by custom routine which accepts dictionary as input
  • Connect to a Class Method by it's method name holded into a var in a for loop in python
  • PyQt5 signals and threading.Timer
  • Replace 2 characters in a string in python
  • Passing command line arguments from a folder script to a file script
  • Understand the syntaxe X[Y == c] in Numpy
  • Optimize beginner python script about substring replacement
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org