logo
Tags down

shadow

Pandas cell value is a column name in another dataframe


By : Matt Hill
Date : September 16 2020, 09:00 AM
may help you . thushv89's answer is good! However, in a different situation you may want to just melt df2.
code :
df2 = df2.melt(id_vars=['Item','Date'],
               value_vars=['Jan','Feb','Mar','Apr','May','Jun'],
               var_name='Month',
               value_name='Demand')
   Item  Date Month  Demand
0     A     1   Jan     343
1     A     2   Jan     340
2     A     3   Jan     373
3     B     1   Jan     345
4     B     2   Jan     348
5     B     3   Jan     346
6     C     1   Jan     456
7     C     2   Jan     452
8     C     3   Jan     451
9     A     1   Feb     335
10    A     2   Feb     331
11    A     3   Feb     334
12    B     1   Feb     456
13    B     2   Feb     450
14    B     3   Feb     459
...


Share : facebook icon twitter icon

Set cell value in Pandas DataFrame based on a value in another DataFrame with same index/column names


By : Olaf Dreyer
Date : March 29 2020, 07:55 AM
To fix the issue you can do Actually you're not far from the solution, in fact, you're thinking right. But if I had to recommend a method I would recommend this using pandas.notnull
code :
df3 = df2[pd.notnull(df1)]
df3 = pd.DataFrame(np.where(pd.isnull(df1),np.nan,df2))
                     33643   33667
1998-01-01 10:00:00    NaN     NaN
1998-01-01 11:00:00    NaN     NaN
1998-01-01 12:00:00    NaN     NaN
1998-01-01 13:00:00    NaN     NaN
1998-01-01 14:00:00  291.1  289.14

How to add column name to cell in pandas dataframe?


By : Forrest Laskowski
Date : March 29 2020, 07:55 AM
it helps some times Make a new DataFrame containing the col*= strings, then add it to the original df with its values converted to strings. You get the desired result because addition concatenates strings:
code :
>>> pd.DataFrame({col:str(col)+'=' for col in df}, index=df.index) + df.astype(str) 
     col1    col2
0  col1=1  col2=3
1  col1=2  col2=4

Python Pandas Dataframe Pulling cell value of Column B based on Column A


By : atcrain
Date : March 29 2020, 07:55 AM
will help you struggling here. Probably missing something incredibly easy, but beating my head on my desk while trying to learn Python and realizing that's probably not going to solve this for me. , you can use .loc method
code :
df.Sales.loc[df.FiscalYear==2007.0]
df.Sales.loc[df.FiscalYear==2007.0].tolist()

Apply function to pandas dataframe to scan a list in a column/cell depending on an other column/cell


By : user1419909
Date : March 29 2020, 07:55 AM
will help you I'm going to show how to split your data into columns corresponding to buttons. I modified input data to be able to fit it nicely in the screen:
code :
import pandas as pd

names = ["B_{}".format(x) for x in range(16)]
df1 = pd.DataFrame(data={'Time': [0, 0.007, 0.014, 0.021, 0.028, 0.035, 0.042, 0.049, 0.056, 0.063],
                    'ID': [['11', '12', '14'], ['12'], ['13'], ['14'], [], [], ['11'], ['12'], ['13'], ['14']],
                    'frames': [['2518', 'B31A', 'AD18'], ['07D0'], ['0BB8'], ['0FA0'], [], [], ['3318'], ['3318'], ['3318'], ['3318']]})

df_new = pd.DataFrame(df1, columns=['Time'] + names)
for index, row in df1.iterrows():
    # copying whatever data you already have in the old dataframe
    df_new.loc[index] = row
    # for every button ID set value in corresponding column
    for ID, value in zip(row['ID'], row['frames']):
        df_new.loc[index, names[int(ID)]] = value
             ID   Time              frames
0  [11, 12, 14]  0.000  [2518, B31A, AD18]
1          [12]  0.007              [07D0]
2          [13]  0.014              [0BB8]
3          [14]  0.021              [0FA0]
4            []  0.028                  []
5            []  0.035                  []
6          [11]  0.042              [3318]
7          [12]  0.049              [3318]
8          [13]  0.056              [3318]
9          [14]  0.063              [3318]
    Time  B_11  B_12  B_14  B_13
0  0.000  2518  B31A  AD18   NaN
1  0.007   NaN  07D0   NaN   NaN
2  0.014   NaN   NaN   NaN  0BB8
3  0.021   NaN   NaN  0FA0   NaN
4  0.028   NaN   NaN   NaN   NaN
5  0.035   NaN   NaN   NaN   NaN
6  0.042  3318   NaN   NaN   NaN
7  0.049   NaN  3318   NaN   NaN
8  0.056   NaN   NaN   NaN  3318
9  0.063   NaN   NaN  3318   NaN

Pandas dataframe multiply entire column by single cell in another column controlling for group identifier


By : user1943692
Date : March 29 2020, 07:55 AM
like below fixes the issue Use div by new Series created by set_index with map and filtered by boolean indexing:
code :
df = pd.DataFrame({
        'statisticsjaar': [1995, 1996, 1997] * 2,
        'activum_statline':['A02'] * 3 + ['A04'] * 3,
        'cumprod':[7,8,9,4,2,3],

})

s = df[df['statisticsjaar'] == 1997].set_index('activum_statline')['cumprod']
print (s)
activum_statline
A02    9
A04    3
Name: cumprod, dtype: int64

df['new'] = df['cumprod'].div(df['activum_statline'].map(s))
print (df)
   statisticsjaar activum_statline  cumprod       new
0            1995              A02        7  0.777778
1            1996              A02        8  0.888889
2            1997              A02        9  1.000000
3            1995              A04        4  1.333333
4            1996              A04        2  0.666667
5            1997              A04        3  1.000000
df = pd.DataFrame({
        'statisticsjaar': [1995, 1996, 1997] * 2,
        'activum_statline':['A02'] * 3 + ['A04'] * 3,
        'cumprod':[7,8,9,4,2,3],
        'statlinebasiscode':['320700'] * 6,
        'niveau':['A38'] * 6,

})

cols = ['activum_statline','statlinebasiscode','niveau']
s = df[df['statisticsjaar'] == 1997].set_index(cols)['cumprod'].rename('new')
print (s)
activum_statline  statlinebasiscode  niveau
A02               320700             A38       9
A04               320700             A38       3
Name: new, dtype: int64

df['new'] = df['cumprod'].div(df.join(s, on=cols)['new'])
print (df)
   statisticsjaar activum_statline  cumprod statlinebasiscode niveau       new
0            1995              A02        7            320700    A38  0.777778
1            1996              A02        8            320700    A38  0.888889
2            1997              A02        9            320700    A38  1.000000
3            1995              A04        4            320700    A38  1.333333
4            1996              A04        2            320700    A38  0.666667
5            1997              A04        3            320700    A38  1.000000
Related Posts Related Posts :
  • How to find the orientation of an object (shape)? - Python Opencv
  • Python Coordinate system question for centering drawn objects
  • appending 2 dataframes together and increment the ranks while appending
  • How to find len with with in list statement
  • Printing the items from a list with the index value of another list?
  • How to rise an exception if an input string is not a given one
  • How to elegantly handle multiple continue statements inside for loop
  • Upgrading tf.contrib.slim manually to tf 2.0
  • Dask read_parquet adds an extra column dir0
  • `pip install --upgrade pip` fails inside a Windows virtualenv with "Access denied"
  • Writting multiple times in a file in a loop using python
  • How can I arrange two faceted side-by-side charts horizontally in Altair?
  • Python: Nested dictionary - create if key doesn't exist, else sum 1
  • Rectangular box pattern X with fill right of 1/4 in python
  • ImportError: cannot import name 'set_random_seed' from 'tensorflow' (C:\Users\polon\Anaconda3\lib\site-packages\tensorfl
  • Flake8 E901 unexpected behavior with print() statement
  • How Do We Convert HTML to PDF using Python, Is there Any code please share it to me?
  • Extract Data from XAML using Python
  • Background image cleaning for OCR
  • Positional and Keyword markers / * syntax error
  • Find value with iat with conditions
  • How to print the same time in milliseconds in python and C++?
  • Python random unique value for multiple variables
  • what is the equivalent function of R's c( ) in python?
  • How to solve the side effects probably caused by list.append()?
  • Why Does Python List Multiplication Create A Single List with Multiple Elements?
  • What does strip() consider whitespace?
  • How to create a master dictionary from a from a dictionary
  • I have two dataframes (DF1) and (DF2). I want to substitute values for a column in (DF2) that match criteria on two colu
  • Change Interpreter in Jupyter notebook
  • Convert Numpy matrix to list with indices as tuples
  • Why dictionary keys get added to a list using extend()?
  • stripping punctuation and finding unique words in Python
  • Sikuli GUI Automation - continuous check for external errors
  • Python3 prints two backslash
  • Pandas df.plot set color proportional to a dataframe column
  • My simple python game wont work please identify my mistakes
  • Lowercase dictionary items within a list python
  • If you don't trust global variables, when you are inside of a method, how do you tell what class we are currently in?
  • Python Pandas update value in row using precedent row value
  • How to convert [2,3,4] to [0,0,1,1,1,2,2,2,2] to utilize tf.math.segment_sum?
  • Should I use numpy.polyfit or numpy.polynomial.polyfit or numpy.polynomial.polynomial.Polynomial?
  • How to set 0-1 matrix using a vector of indices using numpy?
  • Python invalid syntax on scrapy pipeline for mysql
  • ResourceWarning: unclosed file <_io.BufferedReader name=4>
  • Sqlite where query in Python on integer value field not working
  • When Chrome was updated, Selenium stopped working
  • How to sum or count groups of multiple columns in pandas
  • Numpy array ndmin behavior for empty array
  • Password with @ can't connect the database
  • Python how can I print cp1258 vietnamese characters correctly?
  • skip leading number in regular expression?
  • Selenium + Python how to listen for change of element
  • How can to start tasks with celery-beat?
  • Read Latest File from Google Cloud Storage Bucket Using Cloud Function
  • Implement sliding window with three input variables, list, window size and forward move size using python?
  • Replace the data in an excel sheet
  • Populate a Numpy array according to values of two different arrays
  • PySide2 Qthread crash
  • Python: TypeError: string indices must be integers
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk