I want to print a Python dictionary with keys in one row and values in another row.
Example:
d = {'a':'long val', 'b':None, 'long key':3, 'd':4}
I want to print it as
a | b | long key | d
long val | | 3 | 4
How can I do this?
I'd say that either you iterate twice or you build the two output lines first and then display them:
d = {'a': 'long val', 'b': None, 'long key': 3, 'd': 4}
headers = ""
row = ""
for k, v in d.items():
if row != "":
row += " | "
headers += " | "
max_len = max(len(str(k)), len(str(v)) if v else 1)
headers += str(k).center(max_len)
row += str(v).center(max_len) if v else " "
print(headers)
print(row)
But it looks like a lot of hassle to avoid a double iteration over a simple dict.
Ok, here is the updated version, which is scalable
print(*["{!s:^16}|".format(item) for item in d.keys()] )
print(*["{!s:^16}|".format(item) for item in d.values()])
output:
a | b | long key | d
long val | None | 3 | 4
Related
I want to do
df[(df['col']==50) | (df['col']==150) | etc ..]
"etc" is size changing from 1 to many
so I do a loop
result is like
str= "(df['col']==50) | (df['col']==150) | (df['col']==100)"
then I do this
df[str]
but this does not work
How can I make it work ?
A simple solution:
list_of_numbers = [50,150]
df[df["col"].isin(list_of_numbers)]
Where list_of_numbers are the numbers you want to include in the condition. I'm assuming here your condition is always or.
Use query to filter a dataframe from a string
df = pd.DataFrame({'col': range(25, 225, 25)})
l = [50, 100, 150]
q = ' | '.join([f"col == {i}" for i in l])
out = df.query(f)
>>> q
'col == 50 | col == 100 | col == 150'
>>> out
col
1 50
3 100
5 150
Lets say I want to print out
Item 1 | Item 2
A Third item | #4
Which can be done without the | by doing
print('%s20 %20s' % (value1,value2))
How would I go about placing the | character so that it is evenly justified between the two formatted values?
I suppose I could manually could the length of the formatted string without the | character and then insert the | in the middle but I am hoping for a more elegant solution!
Thank you very much for your time.
Edit: Here is a solution that I suggested would be possible
def PrintDoubleColumn(value1, value2):
initial = '%s20 %20s' % (value1,value2)
lenOfInitial = len(initial)
print(initial[:lenOfInitial/2] +'|' + initial[lenOfInitial/2+1:])
There is a good source for string format operations: https://pyformat.info/#string_pad_align
x = [1, 2, 3, 4, 5]
y = ['a', 'b', 'c', 'd', 'e']
for i in range(0, 5):
print "{0:<20}|{1:>20}".format(x[i], y[i])
Result:
1 | a
2 | b
3 | c
4 | d
5 | e
I have a pandas dataframe structured as follows:
| ID | Start | Stop |
________________________________________
| 1 | 1,2,3,4 | 5,6,7,7 |
| 2 | 100,101 | 200,201 |
For each row in the dataframe, I'd like to add 1 to each value in the Start column. The dtype for the Start column is 'object'.
Desired output looks like this:
| ID | Start | Stop |
________________________________________
| 1 | 2,3,4,5 | 5,6,7,7 |
| 2 | 101,102 | 200,201 |
I've tried the following (and many versions of the following), but get an error stating ,TypeError: cannot concatenate 'str' and 'int' objects,:
df['test'] = [str(x + 1) for x in df['Start']]
I tried casting the column as an int, but got 'Invalid literal for long() with base 10: '101,102':
df['test'] = [int(x) + 1 for x in df['start'].astype(int)]
I tried converting the field to a list using str.split(), then casting each item as an integer:
Thanks in advance!
df['Start'] is the whole series, so you have to iterate that and then split:
new_series = []
for x in df['Start']:
value_list = []
for y in x.rstrip(',').split(','):
value_list.append(str(int(y) + 1))
new_series.append(','.join(value_list))
df['test'] = new_series
By telling you that you cannot concatenate string and int objects you know that x must be a string. You can solve this by casting x to an int before adding 1 to it. So str(x+1) becomes str(int(x)+1).
df['test'] = [str(int(x) + 1) for x in df['Start']]
df = pd.DataFrame({'Start' : [ [1 , 2, 3 , 4] , [100 , 101] ] , 'Stop' : [ [5 , 6 , 7 ,7] , [200,201] ] })
df.Start = df.Start.apply(lambda x : [y + 1 for y in x ])
I'm trying to create a 4x3 table without methods or for-loops.
I'd like to use what I learned in class, which is booleans, if-statements, and while-loops.
I want it so that if I input create_table('abcdefghijkl') it would start from the the left top most row and column and go down until the end of the column and then start again at the top of the next column and so on, like displayed below:
| a | e | i |
| b | f | j |
| c | g | k |
| d | h | l |
Below is what I have so far. It's not complete. How do I add to the function so that after 4 rows down, the string should continue to the next column starting from the top?
I'm wracking my brain over this.
All examples I can find online uses for loops and methods to create tables such as these, but I'd like to implement the while loop for this one.
Thanks in advance!
def create_table(table):
t = "" + "|" + ""
i = 0
while i < 12:
t = t + " " + "|" + table[i] + " "
i=i+1
print(t)
return table
Think about it in terms of rows instead of columns. You're writing out a row at a time, not a column at a time, so look at the indices of the individual cells in the original list:
| 0 | 4 | 8 |
| 1 | 5 | 9 |
| 2 | 6 | 10 |
| 3 | 7 | 11 |
Notice each row's cells' indices differ by 4. Find a simple expression for the nth row's cells and the task will become much easier, as you'll essentially be printing out a regular table.
You can translate most for loops to while loops with a simple recipe, so if you figure out how to do it with a for loop, then you are good to go. If you have
for x in s:
{statements}
Make it
i = 0
while i < len(s):
x = s[i]
{statements}
i += 1
It just won't work for some enumerable types that don't support length and indexing, such as generators.
Because you are printing to the terminal, you would want to think about printing each horizontal row, rather than each vertical column. Try something like:
table = 'abcdefghijkl'
i = 0
while i < 4:
print("| {} | {} | {} |".format(table[i], table[i+4], table[i+8]))
i += 1
I have a word length_of_word | repetitions dictionary and I want to make a histogram of that like the one in link below using only python built in functions no numpy or anything like it.
http://dev.collabshot.com/show/723400/
Please help me out at least with some pointers.
I guess you must have a dict that looks like this one, right ?
>>> d = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1}
>>> d
{1: 1, 2: 10, 3: 10, 4: 6, 5: 5, 6: 4, 7: 2, 8: 1}
If so, I have a function that does the trick:
>>> def histo(dict_words):
# Get max values, plus delta to ease display
x_max = max(dict_words.keys()) + 2
y_max = max(dict_words.values()) + 2
# print line per line
print '^'
for j in range(y_max, 0, -1):
s = '|'
for i in range(1, x_max):
if i in dict_words.keys() and dict_words[i] >= j:
s += '***'
else:
s += ' '
print s
# print x axis
s = '+'
for i in range(1, x_max):
s += '---'
s += '>'
print s
# print indexes
s = ' '
for i in range(1, x_max):
s += ' %d ' % i
print s
>>> histo(d)
^
|
|
| ******
| ******
| ******
| ******
| *********
| ************
| ***************
| ***************
| ******************
|************************
+--------------------------->
1 2 3 4 5 6 7 8 9
>>>
Ok, there's a little more work to display values on the left and to format correctly numbers greater than 10 not to have shift in indexes, but I think it's a good start :-)