Goal: Create a tuple consisting of the column headers of a pandas dataframe AND an additional column in a single, easy-to-understand statement.
For the example say:
df.columns = ['a', 'b', 'c']
fname = 'sample.txt'
I can create the tuple ('a', 'b', 'c', 'sample.txt') in three statements as follows:
y = [x for x in df.columns]
y.append(fname)
mytuple = tuple(y)
It's readable, but verbose. I can reduce this to two statements as:
y = [x for x in df.columns].append(fname)
mytuple = tuple(y)
This is not bad, but I still prefer to do it in one line. My thought A is a single line statement should work like this:
mytuple = tuple([x for x in df.columns].append(fname))
Alas, that yields the error:
TypeError: 'NoneType' object is not iterable
I also tried B (wild guess)
mytuple = tuple([[x for x in df.columns].append(fname)])
but that gives the wrong result
(None,)
I would like to know 3 things:
- Why does option A does not work as I think it should.
- Is there a way to do this (non-obtusely) in a single statement.
- If so, how is it done?