logo
Tags down

shadow

Year wise cumsum based on condition on other column Python 3+ Pandas data frame


By : Smed910
Date : October 14 2020, 02:24 PM
This might help you Use numpy.where with DataFrameGroupBy.cumsum:
code :
df['Cumsum'] = np.where(df['Value'] == 0, 0, df.groupby('Year')['PV'].cumsum())
print (df)
   Year  Value  PV  Cumsum
0  2000      0   7       0
1  2000    100   8      15
2  2000      0   9       0
3  2001      0  12       0
4  2001    100  13      25
5  2001    100  14      39


Share : facebook icon twitter icon

Pandas Data Frame filtering based off a column condition


By : J. Doe
Date : March 29 2020, 07:55 AM
wish of those help You can use str.contains to check if a string column contains a sub string:
code :
df[df.Grade.str.contains('2170B')]

#index  Value 1    Grade
#1  2        15    2170B
#2  3        10 NCR2170B
#4  5        30 NCR2170B

Find if some strings are in a pandas data frame ( row wise and column wise operation )


By : TronLegacyUAE
Date : March 29 2020, 07:55 AM
it should still fix some issue You can join your substrings together using the regex "or" operator | and then apply the pd.Series.str.contains method like so:
code :
dataframe['substr_match'] = dataframe.apply(\
  lambda col: col.str.contains('|'.join(check))).any(axis=1)
#   column1 column2  substr_match
# 0       a       a         False
# 1   alike       b          True
# 2       b       c         False
# 3       x  unlake          True
# 4       a    like          True

Pandas data frame replace max value of a column with different column value based on condition


By : JoelLopes
Date : March 29 2020, 07:55 AM
seems to work fine Another way to do -
This filters out and replaces the specific cases from views to ENGAGEMENTS
code :
newdf['views'] = newdf.apply(lambda x: x['ENGAGEMENTS'] if ((x['PRODUCT'].upper()=='DISPLAY') & (x['COST_TYPE']=='CPE')) else x['views'], axis=1)
df['views'].update(newdf['views'])
           Placement#Name  PRODUCT VIDEONAME COST_TYPE  views  IMPRESSIONS  \
0  1.Blend Of Vdx Display  DISPLAY  Features       CPE   1255       778732   
1  1.Blend Of Vdx Display  DISPLAY       TVC       CPE  13373       778732   
2            2.Mobile VDX  Display  Features       CPE    168         1000   
3            2.Mobile VDX  Display  Features       CPE    150         1000   

   ENGAGEMENTS  DPEENGAMENTS  
0        13373          7142  
1        13373          7142  
2          150           160  
3          150           160 

How to get value in a column based on condition in pandas data frame pivot table?


By : codeDonkey
Date : March 29 2020, 07:55 AM
it helps some times I have a MySQL table as shown below: , You can use:
code :
df['received_on'] = pd.to_datetime(df['received_on'])

md = df.pivot_table(
        values='stock', 
        index=['article','price', 'promo_price','delivery_days'], 
        columns='received_on', 
        aggfunc=np.sum)

#sorting columns in descending order
md = md.sort_index(axis=1, ascending=False)

#remove missing rows in first column
md = md.dropna(subset=[md.columns[0]])
#another solution 
#md = md[md.iloc[:, 0].notna()]
print (md)
received_on                               2019-03-25  2019-03-24  2019-03-20
article price  promo_price delivery_days                                    
03D/6H  3082.0 1716.21     24                    0.0         NaN         NaN
L1620S  685.0  384.81      0                     2.0         2.0         3.0
md = md.sort_index(axis=1, ascending=False)

idx = pd.IndexSlice
md1 = md.loc[idx['03D/6H',:,:],:].iloc[[0]]
print (md1)
received_on                               2019-03-25  2019-03-24  2019-03-20
article price  promo_price delivery_days                                    
03D/6H  3082.0 1716.21     24                    0.0         NaN         NaN

Pandas : Compare the columns of a data frame and add a new column & value based on a condition


By : user3388510
Date : March 29 2020, 07:55 AM
should help you out Solution if need first matched value by both conditions with next and iter trick for add default value [0, 0] if no matched:
code :
final = []
for a, b, c in zip(df['class'], df['sec'], df['details']):
    out = []
    for x in c:
        m1 = x['class'] == a 
        if m1 and x.get('sec') == b:
            out.append(x['subjects'])
        elif m1 and 'sec' not in list(x.keys()):
            out.append(x['subjects'])
    final.append(next(iter(out), [0,0]))

df['subjects'] =  final
Related Posts Related Posts :
  • How to create dictionary combinations? Costliest car problem
  • Select each letter in a file, then find its ASCII value (Python)
  • Python: logarithm to base 2 in nested lists
  • Knapsack algorithm, weird behavior (python3)
  • How to use the break between lines in a txt file to start a new list in Python 3
  • Default *key* when accessing dictionary?
  • "TypeError: a bytes-like object is required, not 'str'" during OAuth 2.0 callback request
  • Lat Long won't show on Heatmap with ipyleaflet
  • Python Flask paginate error:paginated page returned 404
  • can't pickle _thread.RLock objects when running tune of ray packge for python (hyper parameter tuning)
  • Python 3: Positions of button and input text in a text box
  • Bijective function between two nested lists (Python)
  • How to get python console logs on my tkinter window instead of a CMD window while executing an exe file created using py
  • how combine '"+variable+"' in python 3
  • How to send a message with discord.py from outside the event loop (i.e. from python-telegram-bot thread)?
  • BytesIO replaces transparency in PNG files with black background
  • Cannot resize and save image of type .tif after patch extraction with tf
  • Pandas Column Names Not Lining Up When .dat File Read
  • Adding an Image to the python GUI from within the script
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org