-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyBasic1.Rmd
122 lines (95 loc) · 2.96 KB
/
PyBasic1.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
---
title: "Python Basic 1"
author: "Raghu Sidharthan"
output:
html_document:
highlight: pygments
---
**Basic Python Commands**
```{python,eval=FALSE}
type(x) #to get the data type of a variable
len(x) #gives the length of the list/array
#Profile functions
import cProfile
cProfile.run('cdfmvna(aa,rr,ss)',sort=1)
# function definition
def square(x):
return x**2
#Get and set working directory
import os
os.getcwd()
os.chdir('C:\\Users\\sidharthanr\\Temp')
os.listdir('C:\\Users\\sidharthanr\\Temp') # lists all files
import sys
sys.exit("Error message") #To stop the program execution progrmatically
sys.path.append('C:\\Temp') #after this modules in this directory can be imported
print("\n".join(sys.path)) # prints all the folders in the system path
#Get Time for time consumed computations
import time
ts = time.time()
hrs = raw_input("Enter Name:") # to enter data from command prompt
del inpMatPD # Delete an object
__val = gc.collect() #Force garbage collection as we are deleting large objects
#Read last N lines from a file
from collections import deque
with open('data.csv', 'r') as f:
q = deque(f, 2) # reads last two lines
```
**Python commands with evaluation**
```{python}
print(list(xrange(4))) #xrange used for iterators
print('4'.zfill(3)) #Padding Zeros in a string
print(5%2) # modulus operator
#Multiple list counters - like a Cartesian product
print([prefix+'_'+elt for elt in ['aa','bb', 'cc'] for prefix in ('p1','p2') ])
```
```{python}
#Equivalent of R match function (with zero indexing)
match = lambda a, b: [ b.index(x) if x in b else None for x in a ]
print(match([2,1],[1,3,1,3]))
```
```{python}
#Subset a list using another Boolean list
from itertools import compress
list_a = [1, 2, 4, 6]
fil = [True, False, True, False]
print(list(compress(list_a, fil)))
```
**Unpacking a list of lists**
```{python}
LofL = [['x01', 'x02'], ['x03', 'x04'], ['x05', 'x06']] # This is a list of list
flat_list = [item for sublist in LofL for item in sublist]
print(flat_list)
# This is equivalent to below
flat_list=[]
for sublist in LofL:
for item in sublist:
flat_list.append(item)
```
**String Operations**
```{python}
s = " \t a string example\t "
print(s.strip())
print(s.rstrip()) #Whitespace on the right side:
print(s.lstrip()) #Whitespace on the left side:
print(s.strip(' \t\n\r')) #strip arbitrary characters to any of these functions like this:
str = "this is string example....wow!!! this is really string";
print(str.replace("is", "was"))
```
**Time and Date**
```{python}
import time
from datetime import datetime
import pytz
print(datetime.fromtimestamp(1284286794)) #Convert seconds from epoch to datetime object
print(datetime.now()) # Current time
print(datetime.now(pytz.timezone('UTC')).astimezone(pytz.timezone('US/Eastern')))
```
**Itertools Pacakge**
```{python}
import itertools
print list(itertools.permutations([1,2,3], 2))
print list(itertools.combinations([1,2,3], 2))
```
```{python}
```