【问题标题】:make upper case and replace space in column dataframe大写并替换列数据框中的空格
【发布时间】:2018-10-29 01:21:03
【问题描述】:

对于熊猫数据框的特定列,我想将元素全部大写并替换空格

import pandas as pd

df = pd.DataFrame(data=[['AA 123',00],[99,10],['bb 12',10]],columns=['A','B'],index=[0,1,2])

# find elements 'A' that are string
temp1 = [isinstance(s, str) for s in df['A'].values]

# Make upper case and replace any space
temp2 = df['A'][temp1].str.upper()
temp2 = temp2.str.replace(r'\s', '')

# replace in dataframe
df['A'].loc[temp2.index] = temp2.values

我明白了

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexing.py:194: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

有什么建议可以避免这个警告,或者有什么更好的方法来做我想做的事情吗?

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    str.upperreplace

    df['A'] = df.A.str.upper().replace('\s+', '', regex=True).fillna(df['A'])
    
           A   B
    0  AA123   0
    1     99  10
    2   BB12  10
    

    【讨论】:

      【解决方案2】:

      您可以通过使用numpy.where 选择要修改的行来大大简化此操作:

      import pandas as pd
      import numpy as np
      
          df = pd.DataFrame(data=[['AA 123',00],[99,10],['bb 12',10]],columns=['A','B'],index=[0,1,2])
      
      
          df['A'] = np.where(df['A'].apply(lambda x: isinstance(x, str)),
                             df['A'].str.upper().str.replace(r'\s', ''),
                             df['A'])
      

      【讨论】:

        【解决方案3】:

        您可以将最后一行替换为

        df.loc[temp2.index, 'A'] = temp2.values
        

        【讨论】:

          猜你喜欢
          • 2021-04-02
          • 1970-01-01
          • 1970-01-01
          • 2016-10-16
          • 1970-01-01
          • 2020-11-29
          • 1970-01-01
          • 1970-01-01
          • 2015-10-12
          相关资源
          最近更新 更多