📜  从 Pandas 中的列名中删除空格

📅  最后修改于: 2022-05-13 01:54:32.219000             🧑  作者: Mango

从 Pandas 中的列名中删除空格

从 pandas 的列名中删除空格并不难,我们可以使用 replace()函数轻松地从 pandas 的列名中删除空格。我们也可以用另一个字符替换空格。让我们一一来看两者的例子。

示例 1:从列名中删除空格

Python
# import pandas
import pandas as pd
  
# create data frame
Data = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
          
        'Location': ['Saharanpur', 'Meerut', 'Agra', 
                     'Saharanpur', 'Meerut'],
          
        'Sales Code': ['muk123', 'roh232', 'may989',
                       'shu564', 'aka343']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# remove special character
df.columns = df.columns.str.replace(' ', '')
  
# print file after removing special character
print("\n\n", df)


Python
# import pandas
import pandas as pd
  
# create data frame
Data = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
          
        'Location': ['Saharanpur', 'Meerut', 'Agra', 
                     'Saharanpur', 'Meerut'],
          
        'Sales Code': ['muk123', 'roh232', 'may989',
                       'shu564', 'aka343']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# replace space with another character
df.columns = df.columns.str.replace(' ', '_')
  
# print file after removing special character
print("\n\n", df)


输出:

示例 2:用另一个字符替换空格

Python

# import pandas
import pandas as pd
  
# create data frame
Data = {'Employee Name': ['Mukul', 'Rohan', 'Mayank',
                          'Shubham', 'Aakash'],
          
        'Location': ['Saharanpur', 'Meerut', 'Agra', 
                     'Saharanpur', 'Meerut'],
          
        'Sales Code': ['muk123', 'roh232', 'may989',
                       'shu564', 'aka343']}
  
df = pd.DataFrame(Data)
  
# print original data frame
print(df)
  
# replace space with another character
df.columns = df.columns.str.replace(' ', '_')
  
# print file after removing special character
print("\n\n", df)

输出: