Code Sample, a copy-pastable example if possible
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data, columns=['_name','age'])
try:
for row in df.itertuples():
val = getattr(row, '_name')
print(val)
except AttributeError:
print('_name column not accessible')
Problem description
DataFrame columns named with a leading underscore are not accessible. While it is possible to rename the column to access the data, Pandas users unfamiliar with this issue might spend a bit of time developing their own workaround. The perplexing thing about this is when the column names are output for inspection you can see the column name with the leading underscore, e.g. print(df.dtypes.index)
[this should explain why the current behaviour is a problem and why the expected output is a better solution.]
Note: We receive a lot of issues on our GitHub tracker, so it is very possible that your issue has been posted before. Please check first before submitting so that we do not have to handle and close duplicates!
Note: Many problems can be resolved by simply upgrading pandas
to the latest version. Before submitting, please check if that solution works for you. If possible, you may want to check if master
addresses this issue, but that is not necessary.
For documentation-related issues, you can check the latest versions of the docs on master
here:
https://pandas-docs.github.io/pandas-docs-travis/
If the issue has not been resolved there, go ahead and file it in the issue tracker.
Expected Output
The expected output is the data from the column whose name begins with an underscore.
Output of pd.show_versions()
Comment From: mroeschke
itertuples()
returns namedtuple
s, so row is no longer a pandas object.
In [14]: row
Out[14]: Pandas(Index=0, _1='Alex', age=10)
These are created with rename=True
, and _name
is an invalid fieldname for namedtuples so:
If rename is true, invalid fieldnames are automatically replaced with positional names.
So this is the expected behavior. This could be better documented in itertuples()
noting this behavior and a link to the documentation.
Comment From: gaetano-guerriero
I think it would be important to document that the silent renaming can happen elsewhere:
>>> df = pd.DataFrame({'a': [1, 2], '_b': [3, 4]})
>>> df.to_dict(orient='records')
[{'a': 1, '_1': 3}, {'a': 2, '_1': 4}]
Comment From: TomAugspurger
@gaetano-guerriero that's a bug. Doing a release today with a fix.
Comment From: mroeschke
This example looks fixed on master. Could use a test
In [16]: >>> df = pd.DataFrame({'a': [1, 2], '_b': [3, 4]})
...: >>> df.to_dict(orient='records')
Out[16]: [{'a': 1, '_b': 3}, {'a': 2, '_b': 4}]
Comment From: arromabofreu
take
Comment From: pranavc28
take
Comment From: jackgoldsmith4
@pranavc28 are you still working on this?
Comment From: G-J-Evans
Leading numbers followed by an underscore cause the same issue.
"1_column"
and "_column"
as column names will both be silently renamed.
"col_column"
as a column name will not be renamed