logo
down
shadow

how to multiply dataframes elementwise and create multi-index -- Python


how to multiply dataframes elementwise and create multi-index -- Python

By : Kelly Hook
Date : November 22 2020, 02:42 PM
Hope that helps You can reindex the two dataframes so their index/column match, and then multiply them:
code :
df1 = pandas.DataFrame([[i*j for i in range(1, 3)] for j in range(2, 5)], index=list('abc'), columns=list('AB'))
print df1
df2 = pandas.DataFrame([[i*10**j for i in range(1, 4)] for j in range(1, 3)], columns=list('abc'))
print df2

df11 = df1.reindex(columns=pandas.MultiIndex.from_product([df1.columns, df2.index]), level=0)
print df11
df22 = df2.T.reindex(columns=pandas.MultiIndex.from_product([df1.columns, df2.index]), level=1)
print df22

df3 = df11.mul(df22)
print df3


Share : facebook icon twitter icon
making multi-index in pandas dataframes in Python?

making multi-index in pandas dataframes in Python?


By : user3737795
Date : March 29 2020, 07:55 AM
I hope this helps you . I have a data set where there is a matrix of numeric values indexed by a time variable. Each matrix is a numpy array (that can be converted into a dataframe with columns corresponding to columns of the matrix). if i have these matrices how can i make them into a single dataframe where each matrix has a time index? specifically: , Given
code :
import pandas as pd

d1 = pd.DataFrame({"a": [1,2,3,4], "b":[10,20,30,40]})
d2 = pd.DataFrame({"a": [10,20,30,40], "b": [1,2,5,6]})
In [177]: pd.concat([d1, d2], keys=['t1', 't2'])
Out[177]: 
       a   b
t1 0   1  10
   1   2  20
   2   3  30
   3   4  40
t2 0  10   1
   1  20   2
   2  30   5
   3  40   6
In [237]: pd.concat([d1, d2], keys=[('t1', 'p1'), ('t2', 'p2')], names=['time', 'position'])
Out[237]: 
                  a   b
time position          
t1   p1       0   1  10
              1   2  20
              2   3  30
              3   4  40
t2   p2       0  10   1
              1  20   2
              2  30   5
              3  40   6
Create new dataframe from multiple multi-index dataframes

Create new dataframe from multiple multi-index dataframes


By : Tarmo Petrovits
Date : March 29 2020, 07:55 AM
hope this fix your issue It's most probably not the best way to do it, but you can do it this way:
code :
years = df['date'].dt.year.unique()

dfs = []
for i in range(100):
    dfs.append(df.query("Year == %d and Season == '1'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '2'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '3'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '4'"  %np.random.choice(years, 1)))

rnd = pd.concat(dfs)
Concat two dataframes and create multi-index from indexes

Concat two dataframes and create multi-index from indexes


By : MatalusMaster
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I think simpliest is reset_index of both df for default indexes, so concat align data nice and last set_index:
code :
df_f = pd.concat([df_1.reset_index(),df_2.reset_index()], axis=1).set_index(['i_1','i_2'])
print (df_f)
            A1 A2 A3 B1 B2 B3
i_1  i_2                     
2411 123122  1  2  3  4  5  6
df_f = pd.concat([df_1,df_2], axis=1)
print (df_f)
         A1   A2   A3   B1   B2   B3
2411      1    2    3  NaN  NaN  NaN
123122  NaN  NaN  NaN    4    5    6
Multiply 2 columns and create a new one in n number of Dataframes in Python

Multiply 2 columns and create a new one in n number of Dataframes in Python


By : dawcorp
Date : March 29 2020, 07:55 AM
around this issue Looks like you mean to assign a y-value to each data frame. The list comprehension is returning a list of values, not assigning to each dfs[n]. The error happens because dfs is a list and needs to be indexed with a number. To assign a y-value to each dfs do this:
code :
for n in range(len(files)):
    dfs[n]['Y value'] = (dfs[n]['X value'] * dfs[n]['Slope']) + dfs[n]['Intercept'] 
Python / Pandas : concatenate two dataframes with multi index

Python / Pandas : concatenate two dataframes with multi index


By : tyleruk
Date : March 29 2020, 07:55 AM
Does that help Use swaplevel with sort_index:
code :
z = pd.concat([x, y], keys=['x', 'y'], axis=1).swaplevel(0,1, axis=1).sort_index(axis=1)
print (z)
    A       B    
    x   y   x   y
0  A0  A2  B0  B2
1  A1  A3  B1  B3
z = pd.concat({'x':x, 'y':y}, axis=1).swaplevel(0,1, axis=1).sort_index(axis=1)
Related Posts Related Posts :
  • Database is not updated in Celery task with Flask and SQLAlchemy
  • Shapely intersections vs shapely relationships - inexact?
  • How to extract a percentage column from a periodic column and the sum of the column?
  • Zombie ssh process using python subprocess.Popen
  • Python regex to capture a comma-delimited list of items
  • joining string and long in python
  • Value Error in python numpy
  • Check if any character of a string is uppercase Python
  • TensorFlow - why doesn't this sofmax regression learn anything?
  • Python Anaconda Proxy Setup via .condarc file on Windows
  • Creating django objects from emails
  • Get spotify currently playing track
  • Select multiple columns and remove values according to a list
  • Python - How to Subtract a Variable By 1 Every Second?
  • Tkinter unable to alloc 71867 bytes
  • How to add Variable to JSON Python Django
  • CSRF token missing or invalid Django
  • Python: writing to a text file
  • Extracting multiple rows from pandas dataframe and converting to columns
  • Pinging a remote PC with Flask, causing server to block
  • Making a fractal graph using a 2D array?
  • Replacing a word in a list with a value from a dict
  • Savefig as eps yields a non-usable eps
  • Crispy-forms InlineRadios don't show my model state
  • Getting Title of a text
  • Python with numpy: How to delete an element from each row of a 2-D array according to a specific index
  • Sending and Receive data from a web page - Selenium
  • KeyError with Pyro4
  • Python module error
  • Python :: Attribute in superclass not available in inheriting subclass
  • Why does greater than and unequal operators work even though only less than and equal operator has been overloaded
  • Input length mismatch scikit
  • Print String in decreasing length
  • Overloading the [] operator in python class to refer to a numpy.array data member
  • Sympy - altering the range of the y axis for a plot
  • How do I programmatically list a DLL's dependencies in C++ or Python?
  • How do I lock window resizing in a Python matplotlib window?
  • Word boundary RegEx search using PyMongo
  • Iterating over a string by only changing one element in the string
  • classification of data where attribute values are strings
  • Validate user input using regular expressions
  • Synchronizing and Resampling two timeseries with non-uniform millisecond intraday data
  • determing the number of sentences, words and letters in a text file
  • Deploying impure Python packages to AWS
  • Navigating between multiple Tkinter GUI frames
  • Python - Do I need to remove instances from a dictionary?
  • How can I get the edited values corresponding to the keys of a dictionary in views.py POST method, passed as a context v
  • differentiate between python function and class function
  • From array create tuples on if condition python
  • Looping over a text file list with python
  • Monitoring a real-time data stream with a flask web-app
  • Bad quality after multiple fade effect with pydub
  • delete rows in numpy array in python
  • What are the possible numpy value format strings?
  • Conditional Selecting of child elements in pdfquery
  • Python: split string by closing bracket and write in new line
  • SyntaxWarning: import * only allowed at module level
  • theano ~ use an index matrix and embeddings matrix to produce a 3D tensor?
  • Django background infinite loop process management
  • How can I use Pandas or Numpy to infer a datatype from a list of values?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co