logo
down
shadow

How do I change the numbers in a cell to the word 'Bus' in Pandas Python


How do I change the numbers in a cell to the word 'Bus' in Pandas Python

By : zheng
Date : October 18 2020, 06:10 PM
Any of those help I have a data frame that has both numbers and text in the same column, all of which are of an object type. How do I convert only the numbers in the cell to int while the text remains as an object? , IIUC using to_numeric with mask
code :
yourdf=df.mask(df.apply(pd.to_numeric,errors='coerce',axis=1).notnull(),'BUS')
yourdf
Out[631]: 
    27   72  27.1  72.1  None None.1 None.2 None.3
0  BUS  BUS  None  None  None   None   None   None
1  MRT  MRT  None  None  None   None   None   None
2  MRT  MRT  None  None  None   None   None   None
3  MRT  MRT  None  None  None   None   None   None
4  BUS  BUS   BUS   BUS  None   None   None   None
5  BUS  BUS   BUS   BUS  None   None   None   None
6  BUS  BUS  None  None  None   None   None   None


Share : facebook icon twitter icon
Extract only numbers from Word table cell into Excel cell

Extract only numbers from Word table cell into Excel cell


By : Orvar Segerström
Date : March 29 2020, 07:55 AM
I hope this helps . Try this UDF and modify to suit your need. It returns a negative one (-1) if there isn't a match for the N'th number in a line of text.
Assuming the text in Word cell has been put into an Excel range (say C3), Hours stored in column D, Rate min in column E, Rate max in column F, then Formulas in:
code :
Option Explicit

Function GetNthNumber(oItem As Variant, Optional Nth As Long) As Double
    Dim sText As String, n As Long, i As Long, oTmp As Variant
    n = Nth
    ' Set to First if argument "Nth" is not passed in
    If n <= 0 Then n = 1
    ' Retrieve the text from the input item
    Select Case TypeName(oItem)
        Case "Range":   sText = oItem.Text
        Case "String":  sText = oItem
        Case Else:      sText = CStr(oItem)
    End Select
    i = 0 ' Initialize counter
    ' Loop through all the words in the text
    For Each oTmp In Split(sText, " ")
        ' Process only if the word is a number
        If IsNumeric(oTmp) Then
            i = i + 1
            ' Check if it's the Nth number
            If i = n Then
                sText = oTmp
                Exit For
            End If
        End If
    Next
    ' Return -1 if there isn't an answer
    If Not IsNumeric(sText) Then sText = "-1"
    GetNthNumber = CDbl(sText)
End Function
Cells(lRow - 1, "J").Value = GetNthNumber(WorksheetFunction.Clean(.cell(9, 2).Range.Text))  'duration (Time to Book?)
Cells(lRow - 1, "K").Value = GetNthNumber(WorksheetFunction.Clean(.cell(12, 2).Range.Text), 1) 'request low rate
Cells(lRow - 1, "L").Value = GetNthNumber(WorksheetFunction.Clean(.cell(12, 2).Range.Text), 2) 'request high rate
Return the list of each word in a pandas cell and the total count of that word in the entire column

Return the list of each word in a pandas cell and the total count of that word in the entire column


By : Nicholas Kachur
Date : March 29 2020, 07:55 AM
This might help you Here is one way that gives the result you want, although avoids sklearn entirely:
code :
def counts(data, column):
    full_list = []
    datr = data[column].tolist()
    total_words = " ".join(datr).split(' ')
    # per rows
    for i in range(len(datr)):
        #first per row get the words
        word_list = re.sub("[^\w]", " ",  datr[i]).split()
        #cycle per word
        total_row = []
        for word in word_list:
            count = []
            count = total_words.count(word)
            val = (word, count)
            total_row.append(val)
        full_list.append(total_row)
    return full_list

df['column2'] = counts(df,'column1')
df
         column1                                    column2
0   apple is a fruit  [(apple, 3), (is, 2), (a, 1), (fruit, 3)]
1        fruit sucks                   [(fruit, 3), (sucks, 1)]
2  apple tasty fruit       [(apple, 3), (tasty, 1), (fruit, 3)]
3   fruits what else        [(fruits, 1), (what, 1), (else, 1)]
4      yup apple map           [(yup, 1), (apple, 3), (map, 1)]
5   fire in the hole  [(fire, 1), (in, 1), (the, 1), (hole, 1)]
6       that is true            [(that, 1), (is, 2), (true, 1)]
Python Pandas Dataframe: change a NaN cell value with a different column from previous row

Python Pandas Dataframe: change a NaN cell value with a different column from previous row


By : TJSE
Date : March 29 2020, 07:55 AM
around this issue I apologize for not posting the actual data from my dataset so here it is:
code :
             Open   High    Low   Last  Change  Settle   Volume  
Date                                                              
2017-05-22  51.97  52.28  51.73  **51.96**    0.49   52.05  70581.0   
2017-05-23    **NaN**  52.44  51.61  52.31    0.24   52.35   9003.0   
2017-05-24  52.34  52.63  51.91  52.05    0.23   52.12  11678.0   
2017-05-25  52.25  52.61  49.49  49.59    2.28   49.84  19721.0   
2017-05-26  49.82  50.73  49.34  50.73    0.82   50.66  11214.0 
missing = df['Open'].isnull() # get nans
new_open = df['Open'].copy() # make copy

# loop missing and test against a True value
# if so, get the 'Last' value at index and
# populate new_open value at index
for i in range(missing.shape[0]):
    if missing[i] == True:
        new_open.iloc[i] = df['Last'][i-1]

# replace the 'Open' values with new 'Open' values
df['Open'] = new_open
Change the cell values , using Pandas (Python)

Change the cell values , using Pandas (Python)


By : user2411029
Date : March 29 2020, 07:55 AM
seems to work fine You could iterate over the column and replace them as needed. Something like this maybe:
code :
counter = 1
result = []
for i in df.iloc[:, 0]:
    if i == "Type address":
        result.append(f"{i} {counter}")
    else:
        result.append(i)
    counter += 1

df.iloc[:, 0] = result
how to count word numbers in python using pandas

how to count word numbers in python using pandas


By : user3584048
Date : March 29 2020, 07:55 AM
Hope this helps If want count number of rows matching condition, so it means number of Trues of mask only use sum:
code :
result = (df['freq']<=2).sum()
result = df['freq'].le(2).sum()
Related Posts Related Posts :
  • Why does my else statement run when my if statement is true?
  • Data access layer in Python
  • Sum of array in python
  • How to upgrade sqlite 3.8.2 to >= 3.8.3
  • Python child class with more methods
  • Remove duplicates from list of strings
  • How to remove lowercase sentence fragments from text?
  • How can I use Python with Mechanize for posting multipart/form-data?
  • How to print a range with decimal points in Python?
  • Where to find a list of all the possible HTML tags in Python?
  • Set serial port pin high using python
  • How to recovery source python code (.py) from .pyo file?
  • Python Script to backup a directory
  • return to first function() at the end of last function()
  • Why am I getting output for -2//4 as -1?
  • I want output None instead of 0
  • Issues running python scripts in Command Prompt (Specifically with command line arguments)?
  • How would I start integrating pyflakes with Hudson
  • Name some non-trivial sites written using IronPython & Silverlight
  • How do I do advanced Python hash autovivification?
  • What is the paste deploy uri syntax?
  • Removing duplicates (within a given tolerance) from a Numpy array of vectors
  • How do constructors and destructors work?
  • QTableWidget signal cellChanged(): distinguish between user input and change by routines
  • Reverse Search Best Practices?
  • Any downsides to UPX-ing my 32-bit Python 2.6.4 development environment EXE/PYD/DLL files?
  • Unit Test Won't Run Tests
  • Use two for loops simultaneously
  • can we display glass bar chart in python with google app engine
  • Scapy install issues. Nothing seems to actually be installed?
  • Why do people write the #!/usr/bin/env python shebang on the first line of a Python script?
  • What does s() mean?
  • ROC AUC value is 0
  • Why is this the value?
  • Best practices for logging in django project
  • Is there a python openid apps-discovery library to get appengine apps onto the apps marketplace
  • Cannot fetch a web site with python urllib.urlopen() or any web browser other than Shiretoko
  • Similar to ``tabnanny``, how can I check that all the python code is using 4 spaces as an indent?
  • Python: object identity question?
  • Multiple For loops, print else only once if condition is not met
  • Select one item from Series and keep the index
  • __repr__ method appears can't be invoked automatically for Exception class
  • Problem with list value (ValueError) in python 3
  • How to get TouchSensor nested under joint in Webots (Python API)
  • How to specify kernel while executing a Jupyter notebook using Papermill's Python client?
  • How to hide password in Database Connection?
  • How to get a list of dictionaries from the following code?
  • 'How to find out noun to which pronoun is referring to' in python
  • Removing a character (^) from each row of panda Dataframe and get unique words in each row
  • Changing a static variable of inherited classes
  • Django Query result comparison with if statement
  • Python: how to merge two dataframe based only on different columns?
  • Filter data by last 3 months and by ID
  • Inplace arithmetic operation versus normal arithmetic operation in PyTorch Tensors
  • How can I add custom signs to spaCy's punctuation functionality?
  • Ensure positive difference of two numbers
  • i keep getting an error that my list index is out of range
  • Is there a way to create gantt charts in python?
  • How to view network weights and bias during training
  • How can I force SAS to wait for a command to fully execute?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk