41688

converting pandas dataframe to contain a dictionary or list of lists

Question:

state Year Month count 0 alabama 2017.0 10.0 31 1 alabama 2017.0 11.0 30 2 alabama 2017.0 12.0 31 3 alabama 2018.0 1.0 31 4 alabama 2018.0 2.0 28 5 alabama 2018.0 3.0 31 6 alabama 2018.0 4.0 30 7 alabama 2018.0 5.0 31 8 alabama 2018.0 6.0 30 9 alabama 2018.0 7.0 14 10 arkansas 2017.0 10.0 31 11 arkansas 2017.0 11.0 30 12 arkansas 2017.0 12.0 31

Can I convert dataframe above to:

Month state alabama {2017:10.0, 2017:11.0, 2017:12.0, 2018:1.0, 2018:2.0, 2018:3.0, 2018:4.0, 2018:5.0, 2018:6.0, 2018:7.0} arkansas {2017:10.0, 2017:11.0, 2017:12.0}

related to <a href="https://stackoverflow.com/questions/47641184/converting-pandas-dataframe-to-contain-a-list" rel="nofollow">converting pandas dataframe to contain a list</a>

based on @Vaishali's comment below, since dictionary cannot contain duplicate keys, this should be ok too:

Month state alabama [[2017,10.0], [2017,11.0], [2017,12.0], [2018,1.0], [2018,2.0], [2018,3.0], [2018,4.0], [2018,5.0], [2018,6.0], 2[018,7.0]] arkansas [[2017,10.0], [2017,11.0], [2017,12.0]]

Answer1:

Try

df.groupby('state').apply(lambda x: list(zip(x['Year'], x['Month']))) state alabama [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0... arkansas [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0)]

Answer2:

In [73]: (df.groupby('state')['Year','Month'] .apply(lambda x: x.values.tolist()) .to_frame('Month') .reset_index()) Out[73]: state Month 0 alabama [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0... 1 arkansas [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0]]

Answer3:

I guess this will work.

d={} for index, row in df.iterrows(): if(d.get(row['state'],0)==0): d[row['state']=[].append(str(row['year'])+" : "+ str(row['month'])) else: d[row['state']] = d[row['state']].append(str(row['year'])+" : "+ str(row['month']))

This will have it like

arkansas ["2017 : 10.0", "2017 : 11.0", "2017 : 12.0"]

Answer4:

Or also

df.groupby('state').apply(lambda x:x[['Year','Month']].values) state alabama [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0... arkansas [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0]]

Recommend

  • Angular 2 - Bootstrap (Ng2-Bootstrap) typeahead implementation
  • How does a double “for” work in list comprehension?
  • Use STL find_if() to find a specific object in a Vector of object pointers
  • Join 2 tables where two sets of numbers overlap within the joining columns
  • How do you copy a MS SQL 2000 database programmatically using C#?
  • Add vertical separator and labels to R barplot
  • Hadoop/map-reduce: Total time spent by all maps in occupied slots vs. Total time spent by all map ta
  • How to get (-8)^0.333333 = -2 in MATLAB?
  • Java catching exceptions and subclases
  • How to deal with SpiderWebPlot in JFreeChart?
  • user , comment association not working, comment.user.email returns No method error?
  • How to merge 2 or more columns into one?
  • Laravel phpunit always 404
  • “undefined symbol: SQLAllocEnv” error in Java [duplicate]
  • wxWidgets: Detecting click event on custom controls
  • Easy Way to Get Averages Based on Names in List
  • Aspect advising other aspects
  • Odd function behaviour with Tkinter
  • use rvest and css selector to extract table from scraped search results
  • How to get the sql state from libpq?
  • Validity Method for Reference Classes
  • if(!isset($_POST[“user”]) ignored and returns Undefined Index
  • Swift string variables localization
  • Transpose table then set and rename index
  • android duplicate provider authority on apps that don't have provider
  • Which browser have this strange user agent? (IOS device)
  • Varnish/Apache Random 503 Errors
  • IE6 changes DOCTYPE to a bad one
  • Cuda Clang and OS X Mavericks
  • JSON encode and decode on PHP
  • R convert summary result (statistics with all dataframe columns) into dataframe
  • Convert SQLite database to XML
  • Make new pandas columns based on pipe-delimited column with possible repeats
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Conversion from string “a” to type 'Boolean' is not valid
  • xtable package: Skipping some rows in the output
  • Custom Tabgroup Appcelerator
  • $wpdb not working in file of WordPress plugin
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Arrays break string types in Julia