修改pandas dataframe中的许多列

时间:2016-10-01 05:12:12

标签: python list pandas dataframe

我已经坚持了一段时间,没有任何谷歌搜索似乎有帮助。

我正在阅读大量原始数据。一些变量作为对象出现,因为源由于各种原因而使用字母丢失(我不关心)。

所以我想通过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-loop简单地调用df(item).describe()

时,我得到了同样的错误

从我(仍然是新手)对Python的理解,这应该工作。我很茫然。 感谢

3 个答案:

答案 0 :(得分:4)

首先,请参阅this answer

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

选项1

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

选项2

df

<强> 示范
考虑数据框df = pd.DataFrame([ [1, 'a', 2], ['b', 3, 'c'], ['4', 'd', '5'] ], columns=['A', 'B', 'C'])

{{1}}

然后两个 选项 都会产生

enter image description here

答案 1 :(得分:0)

怎么回事:

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

答案 2 :(得分: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