Python Pandas - 去除空白
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43332057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas - Strip white space
提问by fightstarr20
I am using python csvkit
to compare 2 files like this:
我正在使用 pythoncsvkit
来比较 2 个文件,如下所示:
df1 = pd.read_csv('input1.csv', sep=',\s+', delimiter=',', encoding="utf-8")
df2 = pd.read_csv('input2.csv', sep=',\s,', delimiter=',', encoding="utf-8")
df3 = pd.merge(df1,df2, on='employee_id', how='right')
df3.to_csv('output.csv', encoding='utf-8', index=False)
Currently I am running the file through a script before hand that strips spaces from the employee_id
column.
目前,我正在通过脚本运行该文件,该脚本会从employee_id
列中去除空格。
An example of employee_id
s:
一个例子employee_id
:
37 78973 3
23787
2 22 3
123
Is there a way to get csvkit
to do it and save me a step?
有没有办法csvkit
做到这一点并为我节省一步?
回答by Andy
You can strip()
an entire Series in Pandas using .str.strip():
您可以strip()
使用.str.strip()在 Pandas 中创建整个系列:
df1['employee_id'] = df1['employee_id'].str.strip()
df2['employee_id'] = df2['employee_id'].str.strip()
This will remove leading/trailing whitespaces on the employee_id
column in both df1
and df2
这将删除employee_id
列上的前导/尾随空格df1
和df2
Alternatively, you can modify your read_csv
lines to also use skipinitialspace=True
或者,您可以修改您的read_csv
行以也使用skipinitialspace=True
df1 = pd.read_csv('input1.csv', sep=',\s+', delimiter=',', encoding="utf-8", skipinitialspace=True)
df2 = pd.read_csv('input2.csv', sep=',\s,', delimiter=',', encoding="utf-8", skipinitialspace=True)
It looks like you are attempting to remove spaces in a string containing numbers. You can do this by:
看起来您正在尝试删除包含数字的字符串中的空格。您可以通过以下方式执行此操作:
df1['employee_id'] = df1['employee_id'].str.replace(" ","")
df2['employee_id'] = df2['employee_id'].str.replace(" ","")
回答by Stephen Rauch
You can do the strip()
in pandas.read_csv()
as:
你可以做strip()
的pandas.read_csv()
是:
pandas.read_csv(..., converters={'employee_id': str.strip})
And if you need to only strip leading whitespace:
如果您只需要去除前导空格:
pandas.read_csv(..., converters={'employee_id': str.lstrip})
And to remove all spaces:
并删除所有空格:
def strip_spaces(a_str_with_spaces):
return a_str_with_spaces.replace(' ', '')
pandas.read_csv(..., converters={'employee_id': strip_spaces})
回答by Vipin
Df['employee']=Df['employee'].str.strip()
回答by Saeed Khan
The best and easiest way to remove blank whitespace in pandas dataframes is :-
删除熊猫数据框中空白的最佳和最简单的方法是:-
df1 = pd.read_csv('input1.csv')
df1["employee_id"] = df1["employee_id"].str.strip()
That's it
就是这样