samrat1
samrat1

Reputation: 49

Python pandas to_csv issue

I am running python program which takes csv data as string, need to sort it and return output as string

input= "Bet,Charle,Daniell,Ada,Eri\n17945,10091,10088,3907,10132\n2,12,13,48,11"

desired output = "Ada,Bet,Charle,Daniell,Eri\n3907,17945,10091,10088,10132\n48,2,12,13,11"

import pandas as pd
from io import StringIO

def sort_csv(input):
  str_data = StringIO(input)
  output_df = pd.read_csv(str_data, sep=",")
  output_df = output_df.sort_index(axis=1)
  output_df.to_csv(path_or_buf='temp.csv', index=False)
  data = open('temp.csv').read()
  return data

I am facing below error TypeError: slice indices must be integers or None or have an index method

pandas package is upgraded, using python 3.4. Any help?

Upvotes: 0

Views: 354

Answers (1)

rahlf23
rahlf23

Reputation: 9019

Here is an implementation that avoids using pandas, and allows for the ability to sort by different columns. Once you break your input string into a list of lists, your specified sorting column (i.e. the list you want to use to sort from your list of lists) is sorted whilst keeping note of the original indices, which are then passed as the sorting key to the other lists. Afterwards, you simply re-join the string together:

x =  "Bet,Charle,Daniell,Ada,Eri\n17945,10091,10088,3907,10132\n2,12,13,48,11"

col_to_sort = 0

sublists = [i.split(',') for i in x.split()]

sorted_list = [[l[i] for i in sorted(range(len(sublists[col_to_sort])), key=lambda k: sublists[col_to_sort][k])] for l in sublists]

print(repr('\n'.join(','.join(k) for k in sorted_list)))

Yields:

'Ada,Bet,Charle,Daniell,Eri\n3907,17945,10091,10088,10132\n48,2,12,13,11'

Upvotes: 2

Related Questions