[英]Python csv file - Open a csv file and take all info from 2 columns, get unique values and then remove some replies(without Pandas)
[英]How to remove all excessive spaces in any csv file read by Pandas without specifying columns?
我的计划是显示一个有序字典,其中包含从任何 csv 读取的 dataframe 的 OrderedDict,有或没有过多空格(初始空格/非初始空格,单词之间的过多空格(双/三重空格))
这些是我在尝试摆脱过多空格时遇到的问题:
通过使用str.strip()
,需要指定列的字符串,它只能与特定的 csv 文件一起使用。
通过在pd.read_csv
的参数中指定sep
,csv 文件中的某些项目将在有序字典中变为“无”。
skipinitialspace()
不能删除其他多余的空格。
此代码的任何解决方法?:
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)
编辑:
附加示例:
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 ')])
我想要的 Output:
OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose')])
OrderedDict([('First Name', 'Tim'), ('Last Name', 'John son')])
OrderedDict([('First Name', 'James'), ('Last Name', 'House')])
刚刚得到解决方案,可以通过使用str.replace()来实现:
df = pd.DataFrame([[f'Ka te', f' Rose '], [f' Tim ', f'John son'], [f'James ', f'House ']], columns=['First Name', 'Last Name'])
for c in df:
df[c] = df[c].str.replace(' ', '')
for i, row in df.iterrows():
d = OrderedDict(zip(row.index.tolist(), row.tolist()))
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.