pandas - Unable to call value_counts on a new column -
i created new column in dataset so:
df['new_col'] = [ true if v > 0 else false v in df.old_col ]
when call value_counts() on new column, works when do
df['new_col'].value_counts() # works fine
but
df.new_col.value_counts()
gives error:
attributeerror: 'list' object has no attribute 'value_counts'
i'm pretty confused why happens...can not use dot syntax on new columns? advice appreciated, thanks!
as noted alexander, looks you've set attribute rather new series. must assign new column using bracket notation:
in [11]: df = pd.dataframe([[1, 2], [3, 4]], columns=['a', 'b']) in [12]: df['c'] = [1, 2] in [13]: type(df.c) out[13]: pandas.core.series.series
without assigning attribute (and pandas doesn't know want column):
in [14]: df.d = [1, 2] in [15]: type(df.d) out[15]: list
you can't access attribute using bracket notation:
in [16]: df['d'] keyerror: 'd'
for reason, use bracket notation consistently throughout code, way - , reader - know it's column... (explicit better implicit).
note: useful behaviour, (for 1 thing) allows set meta-data dataframe. can assign attribute (or method) pd.dataframe
can used dataframe.
in [21]: pd.dataframe.x = 1 in [22]: df.x out[22]: 1
(this can useful, use sparingly!!!)
Comments
Post a Comment