Python Forum
labelling variables of df with map() in loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
labelling variables of df with map() in loop
#1
These are in panda df ,
agree={'1':'agree','0':"don't agree"}

list_agg=["anc_ir_fo_daily","anc_att_vac_neg", "anc_iodine","anc_danger_neg", "bf_firsthour", "bf_sixmonths_neg", "bf_prev_dehy_neg", "gen_ors_zinc" ]


I want to label list_agg with agree dictionary in looping
My code :

for x in list_agg:
df.x=df.x.map(agree)

when I run this code ,

Error like AttributeError:
'DataFrame' object has no attribute 'x'.
Please help also !
Reply
#2
I am not sure if this could help you to solve the problem you are trying to do,
but it is better to use .loc[:, x] pandas indexier instead of direct accessing df.x. Moreover, if you assign column name to a variable, using .loc[:, varname] is (almost) the only right way to get data in the column.
In general, direct access to data in a column, e.g. by df.column_name could cause even unpredictable behavior if you occasionally
touch some DataFrame method instead, e.g. If you have a column named ix, you can not get access to it by df.ix because
.ix is Pandas indexier with predefined behavior.
Reply
#3
Thanks your suggestion is correct , I found the way !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,430 Jul-27-2022, 08:50 PM
Last Post: rob101
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,434 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  how to use 3 variables python loop evilcode1 2 1,629 Nov-12-2021, 11:43 AM
Last Post: jamesaarr
  Creating a variables inside FOR loop zazas321 5 4,039 Sep-16-2020, 04:42 PM
Last Post: Naheed
  Two variables in loop Ferdis 1 1,519 Jul-24-2020, 10:18 AM
Last Post: buran
  Create, assign and print variables in loop steven_tr 10 4,239 May-28-2020, 04:26 PM
Last Post: ndc85430
  Two variables in for loop vipinv23 9 13,886 Aug-26-2019, 05:30 AM
Last Post: newbieAuggie2019
  Operations on indexed variables in loop Fibulavie 1 1,897 Aug-14-2019, 06:07 AM
Last Post: fishhook
  I need help with loop one function and creating variables don 3 2,769 Jan-24-2019, 07:31 AM
Last Post: buran
  I can't figure out how to create variables in a while loop MrCag 1 2,323 May-08-2018, 08:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020