Home > Mobile >  Python mapping in pandas dataframe
Python mapping in pandas dataframe

Time:05-17

I have a text file with numbers listed, e.g.:

XNodes = [4, 4, 16, 21, 21, 26, 27, 35, 44, 45, 55, 76, 79, 92, 100, 108, 120, 126, 132, 139, 151]

I have a pandas df "Nodes_2" with 163 rows. I would like the numbers in XNodes to map to Nodes_2 row IDs and populate a new column (Nodes_2['XNodes']) with a value of 1, all other IDs in that column then fill with 0.

XNodes = pd.read_csv(XNodes.txt, header=None)
XNodes.rename(columns={0:'ID'}, inplace=True)
XNodes['Values']= '1'
IntDict = XNodes.groupby('ID').Values.apply(list).to_dict()
Nodes_2['XNodes']= Nodes_2['ID'].map(IntDict)
Nodes_2.fillna(0, inplace=True)

This code works, but the 1 values are populated with list notation, e.g. "[1]" or "[1,1]" How can I simply populate those values in the df w/o the list notation?

Thank you!

CodePudding user response:

I assume you want your IntDict to have value (in this case, "1") instead of list of values.

You can achieve them by changing

IntDict = XNodes.groupby('ID').Values.apply(list).to_dict()

to

IntDict = dict(zip(XNodes['ID'], XNodes['Values']))
IntDict

{4: '1',
 16: '1',
 21: '1',
 26: '1',
 27: '1',
 35: '1',
 44: '1',
 45: '1',
 55: '1',
 76: '1',
 79: '1',
 92: '1',
 100: '1',
 108: '1',
 120: '1',
 126: '1',
 132: '1',
 139: '1',
 151: '1'}
  • Related