2020年9月21日 星期一

[ Python 常見問題 ] Determine function name from within that function (without using traceback)

 Source From Here

Question
In Python, without using the traceback module, is there a way to determine a function's name from within that function?

Say I have a module foo with a function bar. When executing foo.bar(), is there a way for bar to know bar's name? Or better yet, foo.bar's name?
  1. #foo.py    
  2. def bar():  
  3.     print "my name is", __myname__ # <== how do I calculate this at runtime?  
HowTo
Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context. The given rejection notice is:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.

However, you can still use inspect module to achieve your goal this way:
  1. import inspect  
  2.   
  3. def bar():  
  4.     current_frame = inspect.currentframe()  
  5.     print(f"I am inside function '{current_frame.f_code.co_name}'")  
  6.   
  7. bar()  
inspect.currentframe(): Return the frame object for the caller’s stack frame.
CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

From Types and members:
* frame.f_code: code object being executed in this frame
* frame.f_code.co_name: name with which this code object was defined


Supplement
python 獲取當前函數的函數名sys._getframe().f_code.co_name

[ Python 常見問題 ] Printing Lists as Tabular Data

 Source From Here

Question
I have one list that is used for three headings, and a matrix that should be the contents of the table. Like so:
  1. teams_list = ["Man Utd""Man City""T Hotspur"]  
  2. data = np.array([[121],  
  3.                  [010],  
  4.                  [242]])  
Note that the heading names are not necessarily the same lengths. The data entries are all integers, though. Now, I want to represent this in a table format, something like this:
  1.            Man Utd   Man City   T Hotspur  
  2. Man Utd         1          0           0  
  3. Man City         1          1           0  
  4. Hotspur         0          1           2  
HowTo
There are some light and useful python packages for this purpose:

1. tabulate(pip install tabulate)
  1. from tabulate import tabulate  
  2. print(tabulate([['Alice'24], ['Bob'19]], headers=['Name''Age']))  
Output:
  1. Name      Age  
  2. ------  -----  
  3. Alice      24  
  4. Bob        19  
tabulate has many options to specify headers and table format.
  1. print(tabulate([['Alice'24], ['Bob'19]], headers=['Name''Age'], tablefmt='orgtbl'))  
Output:
  1. | Name   |   Age |  
  2. |--------+-------|  
  3. | Alice  |    24 |  
  4. | Bob    |    19 |  
2. PrettyTable:
  1. from prettytable import PrettyTable  
  2. t = PrettyTable(['Name''Age'])  
  3. t.add_row(['Alice'24])  
  4. t.add_row(['Bob'19])  
  5. print(t)  
Output:
  1. +-------+-----+  
  2. |  Name | Age |  
  3. +-------+-----+  
  4. | Alice |  24 |  
  5. |  Bob  |  19 |  
  6. +-------+-----+  
PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.

3. texttable:
  1. from texttable import Texttable  
  2. t = Texttable()  
  3. t.add_rows([['Name''Age'], ['Alice'24], ['Bob'19]])  
  4. print(t.draw())  
Output:
  1. +-------+-----+  
  2. | Name  | Age |  
  3. +=======+=====+  
  4. | Alice | 24  |  
  5. +-------+-----+  
  6. | Bob   | 19  |  
  7. +-------+-----+  
with texttable you can control horizontal/vertical align, border style and data types.

4. termtables:
  1. import termtables as tt  
  2.   
  3. string = tt.to_string(  
  4.     [["Alice"24], ["Bob"19]],  
  5.     header=["Name""Age"],  
  6.     style=tt.styles.ascii_thin_double,  
  7.     # alignment="ll",  
  8.     # padding=(01),  
  9. )  
  10. print(string)  
Output:
  1. +-------+-----+  
  2. | Name  | Age |  
  3. +=======+=====+  
  4. | Alice | 24  |  
  5. +-------+-----+  
  6. | Bob   | 19  |  
  7. +-------+-----+  


2020年9月16日 星期三

[ Python 常見問題 ] Shuffling Several DataFrames Together

 Source From Here

Question
Is it possible to shuffle several DataFrames together?

For example I have a DataFrame df1 and a DataFrame df2. I want to shuffle the rows randomly, but for both DataFrames in the same way.

Example
  1. import pandas as pd  
  2.   
  3. df1 = pd.DataFrame(data=[[1,2,3],[4,5,6], [7,8,9]], columns=['f1''f2''f3'])  
  4. df2 = pd.DataFrame({'label':[0,1,0]})  


HowTo
I think you can double reindex with applying numpy.random.permutation to index, but it is necessary both DataFrames have same length and same unique index values:
  1. import numpy as np  
  2.   
  3. new_idx = np.random.permutation(df1.index)  
  4. df1 = df1.reindex(new_idx)  
  5. df2 = df2.reindex(new_idx)  


Alternative with reindex_axis:
  1. print (df1.reindex_axis(idx, axis=0))  
  2. print (df2.reindex_axis(idx, axis=0))  





[ Python 常見問題 ] Determine function name from within that function (without using traceback)

  Source From  Here Question In Python, without using the  traceback  module,  is there a way to determine a function's name from within...