在pandas数据框中修改多列

7
我已经被这个问题困扰了一段时间,但是无论我怎么搜索都没有得到帮助。
我正在读取大量的原始数据。由于数据来源使用字母来表示缺失值,因此有些变量会以对象形式出现(我不关心缺失值的具体原因)。
因此,我想通过pandas.to_numeric(___ ,error='coerce') 将相当大的一部分列强制转换为整数或浮点数(我不太关心哪种类型,只要它们是数字就可以)。
逐列进行操作很容易实现:
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')

The error I get is:

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,并确保给出有意义的返回值(即如果无法转换,则返回原始值)。 - Jan
3个回答

8

首先,参考这个答案

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

Option 1

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

Option 2
选项 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'])

那么上面两个选项都会产生以下结果:

输入图像描述


0

它获取两个数据框,第一个是实际数据,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

0
这个怎么样:
df = df.apply( pd.to_numeric, errors='coerce' )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接