【问题标题】:modifying many columns in pandas dataframe修改熊猫数据框中的许多列
【发布时间】:2017-02-09 17:23:23
【问题描述】:

我已经被这个问题困扰了一段时间,而且谷歌搜索似乎无济于事。

我正在阅读大量原始数据。一些变量以对象的形式出现,因为源使用了字母,因为各种原因丢失(我不在乎)。

所以我想通过pandas.to_numeric(___ ,error='coerce') 运行相当大的列子集,只是为了强制将它们强制转换为 int 或 float(同样,我不太在意哪个,只是它们是数字的。

我可以轻松地逐列实现这一点:

df['col_name'] = pd.to_numeric(df['col_name'], errors='coerce') 

但是,我想像这样投射大约 60 列 .. 所以我认为这会起作用:

numeric = ['lots', 'a', 'columns']
for item in numeric:
    df_[item] = pd.to_numeric(df[item], errors='coerce')

我得到的错误是:

Traceback (most recent call last):

File "/Users/____/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

File "<ipython-input-53-43b873fbd712>", line 2, in <module>
df_detail[item] = pd.to_numeric(dfl[item], errors='coerce')

File "/Users/____/anaconda/lib/python2.7/site-packages/pandas/tools/util.py", line 101, in to_numeric
raise TypeError('arg must be a list, tuple, 1-d array, or Series')

TypeError: arg must be a list, tuple, 1-d array, or Series

我尝试了很多版本。这与列表或查看列表有关。当 for 循环只调用 df(item).describe() 时,我得到了同样的错误

根据我(还是新手)对 Python 的理解,这应该可行。我不知所措。 谢谢

【问题讨论】:

  • 看看applymap,一定要给出有意义的返回值(即如果无法转换,则返回原始值)。

标签: python list pandas dataframe


【解决方案1】:

首先看this answer

# Let
numeric = ['lots', 'a', 'columns']

选项 1

df[numeric] = df[numeric].apply(pd.to_numeric, errors='coerce')

选项 2

df.loc[:, numeric] = pd.to_numeric(df[numeric].values.ravel(), 'coerce') \
                       .reshape(-1, len(numeric))

演示
考虑数据框df

df = pd.DataFrame([
        [1, 'a', 2],
        ['b', 3, 'c'],
        ['4', 'd', '5']
    ], columns=['A', 'B', 'C'])

那么上面的两个选项产量

【讨论】:

    【解决方案2】:

    这个怎么样:

    df = df.apply( pd.to_numeric, errors='coerce' )
    

    【讨论】:

      【解决方案3】:

      它得到两个数据框,第一个实际数据和df_data_type包含特征及其类型

      def check_change_data_type(df, df_data_type):
              for i in range(0,len(df_data_type)):
                  #print(df_data_type.iloc[i][0])
              #print(df_data_type.iloc[i][0],"Type",df_data_type.iloc[i][1])
                  for col in df.columns:
                      #print(col)
                      if df_data_type.iloc[i][0] == col:
                          if not df_data_type.iloc[i][1] == df[col].dtype.kind:
                              print("Data Type is not equal", col, df[col].dtype.kind,df_data_type.iloc[i][1])
                              if df_data_type.iloc[i][1] == 'f':
                                  df[col] = df[col].str.replace('[^A-Za-z0-9\s]+', '')
                                  df[col] = pd.to_numeric(df[col], errors = 'coerce')
                                  #df[col] = df[col].apply(pd.to_numeric, errors='coerce')
                                  #df.loc[:,col] = df.loc[:,df.columns.get_loc(col)].apply(''.join).str.replace('[^A-Za-z0-9\s]+', '') 
                                  #df[col] = pd.to_numeric(df[col], errors = 'coerce') 
                              elif df_data_type.iloc[i][1] == 'i' and df[col].dtype.kind != 'f':
                                  df[col] = df[col].str.replace('[^A-Za-z0-9\s]+', '')
                                  df[col] = pd.to_numeric(df[col], errors = 'coerce')
                              elif df_data_type.iloc[i][1] == 'i' and df[col].dtype.kind == 'f':
                                  df[col] = pd.to_numeric(df[col], errors = 'coerce')
                                  #df[col] = df[col].apply(pd.to_numeric, errors='coerce')
                                  #df.loc[:,col] = df.loc[:,df.columns.get_loc(col)].apply(''.join).str.replace('[^A-Za-z0-9\s]+', '') 
                                  #df[col] = pd.to_numeric(df[col], errors = 'coerce')
                              #elif df_data_type.iloc[i][1] == 'O':
                          #else: continue
                          else: break        
              
              return df
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 2023-02-02
        • 2022-06-22
        • 2021-12-29
        • 2021-05-27
        • 1970-01-01
        • 2020-08-06
        • 1970-01-01
        相关资源
        最近更新 更多