remove spaces from csv field but ignoring datetime objec - python

i have a csv that is a result of a DB2 query.
For some reason the csv is created like this
"filed1 ", "field2, ","2017-11-24"
i'm able to remove the white spaces inside field with this:
for result in results:
result = [x.strip(' ') for x in result]
csvwriter.writerow(result)
but the date field is <type 'datetime.date'> so i get the error
AttributeError: 'datetime.date' object has no attribute 'strip'
How can i apply the strip function only to string object? Or can i transform the datetime.date object in str object?
Thanks very much

You could change your list comprehension as follows:
result = [str(x).strip() for x in result]
This will first convert all the cells to a string and then apply the strip() on that. Or more directly as follows:
csvwriter.writerow([str(x).strip() for x in result])

Just check the type before:
if isinstance(x,str):
...

Related

Convert String of List to List in Python

I need to convert a string of list to List in Python. I have seen many of the similar questions but none of them works in this case.
I am passing some values through PostMan.
The key passing as a form data
Key = controls
value = [CR1,CR2]
I am fetching the data like this
c_list = self._kwargs['data'].get('controls', [])
print(c-list)
print(type(c-list))
I am getting the following o/p
[CC-2,CC-3]
<class 'str'>
But I need to get it as a list so I have tried the following method
import ast
c_list = self._kwargs['data'].get('controls', [])
res = ast.literal_eval(c_list)
But I am getting the following Error
malformed node or string: <_ast.Name object at 0x7f82966942b0>
You could simply do the following: strip the brackets and split on the commas
>>> s = "[CC-2,CC-3]"
>>> s.strip('[]').split(',')
['CC-2', 'CC-3']

'tuple' object has no attribute 'startswith' when stripping first and last quote from the string in pandas

I am trying to get rid of single quotes around nested dictionaries in pandas data frame (the first element and last element of an object). I am looping through each row in column metadata.
Example of the nested dictionary that is hidden inside of the quotes is below:
'{"dek": "<p>Don\'t forget to buy a card</p>", "links": {"edit": {"dev": "//patty-menshealth.feature.hearstapps.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c", "prod": "//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c"}}}'
I tried the following:
def string_format(df):
for text in df.iteritems():
if text.startswith("'") and text.endswith("'"):
text = text[1:-1]
return text
string_format(df["metadata"])
Returns AttributeError: 'tuple' object has no attribute 'startswith'
You're using pandas.Series.iteritems which in fact iterate over (index, value) tuples. So to make your code work, you should try changing your loop like this:
for label, text in df.iteritems():
# process text
But i suggest you checking out pandas documentation on working with text. For example, you can index your Series directly via .str accessor.

How to extract numbers from excel cell

I want to get only the numbers from a cell (excel). I tried the following:
uzemelteto = first_sheet.cell(17, 11)
res = [int(i) for i in uzemelteto.split() if i.isdigit()]
print res
But it gives an error like: AttributeError: 'Cell' object has no attribute 'split'
How can I modify it, to be able to get only digits?
worksheet.cell() returns an object, namely an instance of the class Cell (docs).
A Cell object has a property value, so instead of
uzemelteto.split()
use
uzemelteto.value.split()
or, to be super safe, because the type of cell.value may vary based on the content, you can use
str(uzemelteto.value).split()

'int' object and 'float' object not callable error

I have a post request returning a list: [u'2']
I am trying to extract the number and turn it into and integer but I keep getting either 'float' object not callable or 'int' object not callable.
Here is what I have tried so far:
speed = [u'2']
strSpeed = speed[3]
intSpeed = int(strSpeed)
and
strSpeed = speed[3]
intSpeed = float(strSpeed)
and
strSpeed = speed[3]
intSpeed = int(float(strSpeed))
It seems that I can do:
print float(strSpeed)
but I can't return it.
Any ideas?
You have a list of Unicode strings:
>>> speed
[u'2']
Obtain the first item from the list, it's a Unicode string:
>>> speed[0]
u'2'
Convert this string to an integer:
>>> int(speed[0])
2
Here you are.
Your speed variable has only a single item, so you can only access index [0]
>>> int(speed[0])
2
>>> speed[0]
'2'
The u is a prefix to declare a unicode string literal. So speed is just a list with a single unicode string.
Not sure exactly what you are trying to do but if you have a list of string items and you want to extract and convert to integters or floats, you could do the following:
stringlist = ["1", "2", "3.2"]
intlistitem = int(stringlist[0])
print(intlistitem)
floatlistitem = float(stringlist[2])
print(floatlistitem)

Converting tuple into list does not work

I query my SQlite Database with a loop to retrieve data from it.
connector = sqlite3.connect("somedb.db")
selecter = connector.cursor()
selecter.execute(''' SELECT somedata FROM somedb''')
for row in selecter:
l = list(row)
print (l)
print (type(l))
Then I try do use formatting to append the retrieved data to something else
this = detect.that( "{}", pick, summary).format(l)
But it comes back with this:
AttributeError: 'tuple' object has no attribute 'format'
I also tried this
s = " ".join(str(row) for row in selecter)
for the l = list(row) statement but it comes back with the same errormessage and it seems that it converts all my 50 separate selections into one string what I dont want.
However, when I run this
print (type(l))
or
print (type(s))
it returns me list or stringas a type. So the converting worked, but the .format does not take it because it thinks it is a tuple.
How comes?
Change your detect.that line to this:
this = str(detect.that("{}", pick, summary)).format(1)

Categories