I'm trying to append cell value using openpyxl, by appending the value directly.
this works:
wb1=load_workbook('test.xlsx')
ws1=wb1.active
testlist=('two','three','four','five')
for i in testlist:
ws1['A1'].value = ws1['A1'].value +(' ') + i
print(ws1['A1'].value)
A1 has a value of "one", after the loop runs it has "one two three four five"
But is it possible to use the append method directly on the cell value?
for i in testlist:
ws1.append['A1'].value = i
however this throws an error
"TypeError: 'method' object does not support item assignment"
The error "method' object is not subscriptable" means that, you are treating an object as python dict or dict like object which the object isn't. Because the append method returns None.
As per documentation of openpyxl, You can worksheet.append via:
A list: all values are added in order, starting from the first column.
which is your case. simply doing the following should work:
wb1=Workbook()
ws1=wb1.active
testlist=('one','two','three','four','five')
# append each element side by side in a single row
ws1.append(testlist)
# To append each element vertical direction in new row you can un-comment next 2 lines.
#for entry in testlist:
# ws1.append([entry])
wb1.save('test.xlsx')
A dict: values are assigned to the columns indicated by the keys (numbers or letters). This might help if you are targeting a specific column.
Or To have more control simply use worksheet.cell.
You will need to move the tuple into a string and can add it to cell A1 like this.
wb1=Workbook()
ws1=wb1.active
testlist=('one','two','three','four','five')
myString = ' '.join(map(str, testlist))
myString.strip()
ws1['A1'].value = myString
wb1.save('test1.xlsx')
Related
I have a 3d list 6 items long and 6 items wide, which is a list of lists of a list of strings.
lst = [ [['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
[['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
[['A'],['A'],['B'],['B'],['A'],['A']],
[['B'],['B'],['A'],['A'],['B'],['B']],
]
I want to move the strings into other locations on the list, but I know I'm not using the right code:
lst.insert([1][0][0], 'A')
gives me a TypeError: 'int' object is not subscriptable
I know how to add items by doing this:
lst2 = lst[0][0]
lst2.append('A')
(adds another 'A' string to the first item)
I want to perform various actions on the lowest list like:
add/remove strings to that list,
check how many string items are in that list
move 'A' or 'B' strings to different locations so that they have multiple strings.
Check to see what the first string is in the list is
I am very new to programming and I am just starting to understand how to use 2d lists.
How do I accomplish this without any additional modules or libraries?
First of all, let me clarify this line:
lst.insert([1][0][0], 'A')
The insert method expects an int argument for the index. If you want to insert an element in a multidimensional list it should be done as:
lst[1][0].insert(0, 'A')
After all, it is a list of list (of lists). Only if you look at an inner index (defined by 2 coordinates), will you get a simple list (of strings in this case). You can then insert a string element to this simple list, by calling the insert() method.
check how many string items are in that list
count = 0
for d2 in lst: #d2 is a 2d list (an element of a 3d list)
for d1 in d2: # d1 - 1 dimensional
count += len(d1)
Here, I have gone through each of the lowermost-level (simple) lists using a nested loop, counted how many elements are there in each and added them up.
move 'A' or 'B' strings to different locations so that they have multiple strings.
Say I want to move the element from [3][2][0] to [1][2][1]. I would insert it in the new position and then delete from the old.
element = lst[3][2][0] # the task can be accomplished without using another variable, but this is for better understanding
lst[1][2].insert(1, element) # inserting
lst[3][2].pop(0) # deleting
The element could even be moved to a position like [1][2]. So there would be one string along with the other 'sub-lists'
Check to see what the first string is in the list is
Do you mean lst[0][0][0].
So I created a new column in my dataframe using a list. Now every entry has the ‘[ ]’ squared parentheses around the text. How do I remove them? Please help! It seems easy but I’m not getting there. Code used:
df.insert(1, ‘Email’, emails_list, True)
Now all the data in the Email column is in [square brackets]. I want to remove those parentheses.
You probably have lists as values to each row in the column 'Email'. You can try the below code to take the first element of the list, and replace the original list with it.
df['Email'] = df['Email'].map(lambda x: x[0] if len(x)> 0 else '')
The above code takes each cell value of the column, and checks if it of non zero length. If it has non-zero length, then it replaces the list in the cell, with the first element of the list. Otherwise, it just replaces it with an empty string.
This should help. If the error persists, please check the type and shape of 'emails_list'
I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.
for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call
https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.
EDIT:
for i,j in enumerate(dict1.keys()): j = somethingElse
EDIT2:
I think the problem may be with pandas. The first line works, not the second.
for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])
EDIT3:
That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:
for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])
EDIT4:
According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:
listOfFrame = []
for j in dict.keys():
j = pd.DataFrame(dict[j]['Values'])
listOfFrame.append(j)
Indeed j will be a str (or whatever else type of key you are using in dict).
The actual problem is with the loop body, as the error message states:
str(j) = somethingElse
is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.
Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:
dfs = []
for val in dict1.values():
dfs.append(pd.DataFrame(val['Values']))
However, this would normally written without an explicit loop in Python, for instance by using list comprehension:
dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]
From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
so i want to remove an item from a list and store it into the variable at the same time in python. I tried a sample code like this:
rvals = []
rvals.append("row")
r = rvals.remove("row")
print(r)
but it turns out this doesnt really work and it gives r a NoneType value instead of removing what i wanted and storing it. Is there a way to do this?
list.remove(x)
Remove the first item from the list whose value is x. It is an error
if there is no such item.
So, as stated in the docs, you will not get the value returned.
This can help:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop(rvals.index(value))
Or just use pop(), if you only want to remove and get the last inserted item:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop()
Output:
row
Printing a removed element from the list using remove() method generally results in None.
Hence, a better approach is to, first store the element to be removed and then remove it from the list.
User sets values manually in all cells in a QTableWidget. The values of the first row of the table represent the values we want to store in a dictionary FirstRowDict. Second row values will be put in SecondRowDict and so on.
So from a table like one shown in the picture,
we want to end up in this example with FirstRowDict={0:10,1:20}
and SecondRowDict={0:30,1:40}
To achieve this i created a button and added an action that updates the target dictionaries when clicked:
def button_click():
for j in range(0,2):
FirstRowDict.update({i: float(str(tablewidget.itemAt(0,j).text()))})
#I put "0" in itemAt because first row is zero
#tablewidget = QTableWidget() declared earlier in the source code
SecondRowDict.update({i: float(str(tablewidget.itemAt(1,j).text()))})
print '1st_Row_Dict=%s'%1st_Row_Dict,'\n2nd_Row_Dict=%s'%2nd_Row_Dict
The output is not correct since the dictionaries are populated with same value and not the unique value of each cell.
I get FirstRowDict={0:10,1:10} and SecondRowDict={0:10,1:10}
It seems that i have to create a new item using QTableWidgetItem http://doc.qt.nokia.com/4.7-snapshot/qtablewidget.html#item
Python begginer, some advice would be appreciated.
Ah, I see the confusion. itemAt returns the item at the given position, but it's not row/column. It's the coordinate (think of it as pixel).
Yes, you should use item instead of itemAt.
You don't need a str if you're going to convert it to float. float() will work on a QString as if it was a str. And, instead of .update, you can just assign the new value to the key.
FirstRowDict[i] = float(tablewidget.item(0, j).text())