简体   繁体   English

Pandas - 去除空白

[英]Pandas - Strip white space

I am using python csvkit to compare 2 files like this:我正在使用 python csvkit来比较这样的 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做到这一点并为我节省一步?

You can strip() an entire Series in Pandas using .str.strip() :你可以strip()使用整个系列在熊猫.str.strip() :

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这将删除df1df2 employee_id列上的前导/尾随空格

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(" ","")

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})
Df['employee']=Df['employee'].str.strip()

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就是这样

To strip whitespace from all the columns or variable we can use str.strip() function with lambda. 要从所有列或变量中去除空格,我们可以将str.strip()函数与lambda一起使用。

df = df.apply(lambda x: x.str.strip())

To strip whitespace from single column or variable we can use str.strip() function on the pandas series or column. 要从单列或变量中去除空格,我们可以在pandas系列或列上使用str.strip()函数。

df['column1'] = df['column1'].str.strip()

To strip whitespace from data frame/ pandas column name or header 从数据框/熊猫列名称或标题中删除空格

df.columns = df.columns.str.strip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM