Fix Python – Explicitly select items from a list or tuple

I have the following Python list (can also be a tuple):
myList = [‘foo’, ‘bar’, ‘baz’, ‘quux’]

I can say
>>> myList[0:3]
[‘foo’, ‘bar’, ‘baz’]
>>> myList[::2]
[‘foo’, ‘baz’]
>>> myList[1::2]
[‘bar’, ‘quux’]

How do I explicitly pick out items whose indices have no specific patterns? For example, I want to select [0,2,3]. Or from a very big list o….

Fix Python – Update row values where certain condition is met in pandas

Say I have the following dataframe:

What is the most efficient way to update the values of the columns feat and another_feat where the stream is number 2?
Is this it?
for index, row in df.iterrows():
if df1.loc[index,’stream’] == 2:
# do something

What to do if I have more than a 100 columns? I don’t want to explicitly name th….

Fix Python – Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b?

As we all know, the pythonic way to swap the values of two items a and b is
a, b = b, a

and it should be equivalent to
b, a = a, b

However, today when I was working on some code, I accidentally found that the following two swaps give different results:
nums = [1, 2, 4, 3]
i = 2
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
# [1….

Fix Python – What rules does Pandas use to generate a view vs a copy?

I’m confused about the rules Pandas uses when deciding that a selection from a dataframe is a copy of the original dataframe, or a view on the original.
If I have, for example,
df = pd.DataFrame(np.random.randn(8,8), columns=list(‘ABCDEFGH’), index=range(1,9))

I understand that a query returns a copy so that something like
foo = df.query(‘2 < ind....

Fix Python – In Python, how do I index a list with another list?

I would like to index a list with another list like this
L = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]
Idx = [0, 3, 7]
T = L[ Idx ]

and T should end up being a list containing [‘a’, ‘d’, ‘h’].
Is there a better way than
T = []
for i in Idx:

print T
# Gives result [‘a’, ‘d’, ‘h’]