My plan is to display an Ordered dictionary with OrderedDict of a dataframe read from any csv with or without excessive spaces (initial spaces/non initial spaces, excessive spaces(double/tripe spaces) in between words)
These are the problems I encountered while trying to get rid of excessive spaces:
By using
str.strip()
, the string of columns are needed to be specified, which can only work with specific csv file.By specifying
sep
in the parameter ofpd.read_csv
, some of the items in the csv file will turn into 'None' in an ordered dictionary.skipinitialspace()
can't remove other excessive spaces.
Any workaround for this code?:
file = input("Input any csv file or file path \nYour input: ")
df = pd.read_csv(file)
for i, row in df.iterrows():
d = OrderedDict(zip(row.index.tolist(), row.tolist()))
print(d)
Edit:
Additional example:
df = pd.DataFrame([[f'Ka te', f' Rose '], [f' Tim ', f'John son'], [f'James ', f'House ']], columns=['First Name', 'Last Name'])
for i, row in df.iterrows():
d = OrderedDict(zip(row.index.tolist(), row.tolist()))
print(d)
Output:
OrderedDict([('First Name', 'Ka te'), ('Last Name', ' Rose ')])
OrderedDict([('First Name', ' Tim '), ('Last Name', 'John son')])
OrderedDict([('First Name', 'James '), ('Last Name', 'House ')])
The Output that I want:
OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose')])
OrderedDict([('First Name', 'Tim'), ('Last Name', 'John son')])
OrderedDict([('First Name', 'James'), ('Last Name', 'House')])