logo
down
shadow

Fill in empty value in a dataframe column with the same value if it already exists in another row


Fill in empty value in a dataframe column with the same value if it already exists in another row

Content Index :

Fill in empty value in a dataframe column with the same value if it already exists in another row
Tag : python , By : user152319
Date : November 29 2020, 04:01 AM

this one helps. Try this, create a series of those Items with stats, then use map to get stats for all items:
mapper = df[df.Stats.notnull()].set_index('Item')['Stats']
df['Stats'] = df['Item'].map(mapper)
print(df)
    Hero    Item                  Stats
0      1  Item 1       10 HP, 10 Damage
1      1  Item 2  10 Armor, 10 Tenacity
2      1  Item 3  10% Healing, 10 Armor
3      1  Item 3  10% Healing, 10 Armor
4      2  Item 4         10 Skill Power
5      2  Item 5  10 HP, 10 Skill Power
6      2  Item 3  10% Healing, 10 Armor
7      2  Item 1       10 HP, 10 Damage
8      3  Item 1       10 HP, 10 Damage
9      3  Item 4         10 Skill Power
10     3  Item 5  10 HP, 10 Skill Power
11     3  Item 2  10 Armor, 10 Tenacity
12     4  Item 6                 5 Crit
13     4  Item 1       10 HP, 10 Damage
14     4  Item 4         10 Skill Power
15     4  Item 7         25 Skill Power

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Fill a dataframe column with empty arrays


Tag : python , By : TomL
Date : March 29 2020, 07:55 AM
I wish this help you You can repeat the np.empty into number of rows and then assign them to the column. Since it aint a scalar it cant be directly assigned like df['x'] = some_scalar.
df = pd.DataFrame({'a':[0,1,2]})

df['c'] = [np.empty(0,dtype=float)]*len(df)
  a   c
0  0  []
1  1  []
2  2  []

fill up empty values with same value of another column in pandas dataframe


Tag : python , By : Lars
Date : March 29 2020, 07:55 AM
should help you out I think you need groupby + transform:
If only one same category per group and no data are empty strings :
df['POLICY NUMBER'] = (df.groupby('PRODUCT TYPE')['POLICY NUMBER']
                         .transform(lambda x: x[x != ''].iat[0]))

print (df)
  POLICY NUMBER PRODUCT TYPE
0     433M86968          MED
1     433M86968          MED
2     433M86968          MED
3     433M86968          MED
4    566D158635          TED
5    566D158635          TED
6    566D158635          TED
7    566D158635          TED
df['POLICY NUMBER'] = (df['POLICY NUMBER'].str.strip().groupby(df['PRODUCT TYPE'])
                                  .transform(lambda x: x[x != ''].iat[0]))

print (df)
  POLICY NUMBER PRODUCT TYPE
0     433M86968          MED
1     433M86968          MED
2     433M86968          MED
3     433M86968          MED
4    566D158635          TED
5    566D158635          TED
6    566D158635          TED
7    566D158635          TED
df['POLICY NUMBER'] = (df.sort_values(['PRODUCT TYPE','POLICY NUMBER'])
                         .groupby('PRODUCT TYPE')['POLICY NUMBER']
                         .transform('last'))
print (df)
  POLICY NUMBER PRODUCT TYPE
0     433M86968          MED
1     433M86968          MED
2     433M86968          MED
3     433M86968          MED
4    566D158635          TED
5    566D158635          TED
6    566D158635          TED
7    566D158635          TED
df['POLICY NUMBER'] = (df['POLICY NUMBER'].str.strip()
                                          .replace('',np.nan)
                                          .groupby(df['PRODUCT TYPE'])
                                          .transform(lambda x: x.bfill().ffill()))

print (df)
  POLICY NUMBER PRODUCT TYPE
0     433M49763          MED
1     433M49763          MED
2     433M49763          MED
3     433M86968          MED
4    566D158635          TED
5    566D158635          TED
6    566D158635          TED
7    789D158635          TED  

How do I check if a DataFrame column value exists in any of multiple lists, and if not, fill another column?


Tag : python , By : Joe Sweeney
Date : March 29 2020, 07:55 AM
wish of those help I'm trying to fill df['Group'] with either 'boys', 'girls', or 'both' if their respective df['Color'] values exist within any of the lists or fill NaN in df['Group'] if the df['Color'] value doesn't exist in any of the lists. , You can create a dictionary:
dct = dict(boys = ['Brown', 'Green'],
           girls = ['Violet', 'Verde'],
           both = ['Black', 'White'])

dct = {i: k for k, v in dct.items() for i in v}
{'Brown': 'boys',
 'Green': 'boys',
 'Violet': 'girls',
 'Verde': 'girls',
 'Black': 'both',
 'White': 'both'}
df['Group'] = df['Color'].map(dct)
    Color  Group
0   Brown   boys
1   Green   boys
2   Black   both
3   White   both
4   Verde  girls
5  Purple    NaN
6  Violet  girls

Fill empty Dataframe with filled Dataframe and different column names


Tag : python , By : user177910
Date : March 29 2020, 07:55 AM
Hope that helps IIUC, you can rename the second dataframe and then reindex the columns to the original empty dataframe columns:
Creating the empty data frame:
s = 'TERMID,NAME,TYP,NAMECHANGE,ALIASES,SUCHREGELN,ZUW,SEOTEXT1,SEOTEXT2,SEOKommentar,DBIKommentar'
df = pd.DataFrame(columns=s.split(','))
Empty DataFrame
Columns: [TERMID, NAME, TYP, NAMECHANGE, ALIASES, SUCHREGELN, ZUW, SEOTEXT1, SEOTEXT2, SEOKommentar, DBIKommentar]
Index: []
d = {'one': 'TERMID', 'two': 'TYP', 'three': 'ZUW', 'four': 'SEOKommentar'}
df = df1.rename(columns=d).reindex(columns=df.columns)
   TERMID  NAME  TYP  NAMECHANGE  ALIASES  SUCHREGELN  ZUW  SEOTEXT1  \
0     1.0   NaN  4.0         NaN      NaN         NaN  2.4       NaN   
1     2.0   NaN  3.0         NaN      NaN         NaN  4.4       NaN   
2     3.0   NaN  2.0         NaN      NaN         NaN  7.0       NaN   
3     4.0   NaN  1.0         NaN      NaN         NaN  9.0       NaN   

   SEOTEXT2  SEOKommentar  DBIKommentar  
0       NaN           6.4           NaN  
1       NaN           4.1           NaN  
2       NaN           1.0           NaN  
3       NaN           5.0           NaN  

How to fill in empty column in a dataframe with a particular element from the list of another column?


Tag : python , By : eataix
Date : March 29 2020, 07:55 AM
I hope this helps you . Having a dataframe consisting of a person and the order... , Use str method to slice
In [324]: df['order'].str[3]
Out[324]:
0       fish
1        NaN
2    chicken
3        NaN
Name: order, dtype: object
In [328]: df['main_meal'] = df['order'].str[3].fillna('none')

In [329]: df
Out[329]:
  person                                 order  elements main_meal
0  Alice  [drink, snack, salad, fish, dessert]         5      fish
1    Tom                        [drink, snack]         2      none
2   John         [drink, snack, soup, chicken]         4   chicken
3   Mila                  [drink, snack, soup]         3      none
Related Posts Related QUESTIONS :
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com