Python 从列中减去每列的平均值并返回

Python 从列中减去每列的平均值并返回,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个包含许多列的数据集。我必须创建一个函数,它获取每一列的平均值,然后从列中的每一行中减去它,然后返回减去这些平均值的数据集。我在这里发现了一个类似的问题,并应用了答案,但我一直得到一个错误。这是我的密码: def exercise1(df): df1 = DataFrame(df) df2 = df1 - df1.mean() return df2 exercise1(data) # Where data is the a csv file regarding

我有一个包含许多列的数据集。我必须创建一个函数,它获取每一列的平均值,然后从列中的每一行中减去它,然后返回减去这些平均值的数据集。我在这里发现了一个类似的问题,并应用了答案,但我一直得到一个错误。这是我的密码:

def exercise1(df):
    df1 = DataFrame(df)
    df2 = df1 - df1.mean()
    return df2

exercise1(data)

# Where data is the a csv file regarding salaries in the San Francisco area. 

我得到以下错误

TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

TypeError:ufunc'subtract'不包含签名类型与dtype匹配的循环(“您可以使用
try except对列执行for循环:

def exercise1(df):
    df1 = df.copy()
    for col in df1.columns:
        try:     # if we can compute the mean then substract
            df1[col] -= df1[col].mean()
        except:  # otherwise just ignore the column
            pass

    return df1

您可以使用
try except对列执行for循环:

def exercise1(df):
    df1 = df.copy()
    for col in df1.columns:
        try:     # if we can compute the mean then substract
            df1[col] -= df1[col].mean()
        except:  # otherwise just ignore the column
            pass

    return df1

您需要指定要从中减去的列:

df = {'values1': [1,2,3], 'values2': [4,5,6]}
def exercise1(df):
    df1 = pd.DataFrame(df)
    df2 = df1['values2'] - df1['values2'].mean()
    return df2

print(exercise1(df))

您需要指定要从中减去的列:

df = {'values1': [1,2,3], 'values2': [4,5,6]}
def exercise1(df):
    df1 = pd.DataFrame(df)
    df2 = df1['values2'] - df1['values2'].mean()
    return df2

print(exercise1(df))
expndtw-1.df.mean()生成一个仅包含原始数据帧中的数字列的pandas系列数据类型

means = df.mean()
您可以使用以下方法获取该系列的索引值:

means.index
使用此选项对原始数据帧进行切片并减去平均值

df2 = df[means.index] - means
expndtw-1.df.mean()生成一个仅包含原始数据帧中的数字列的pandas系列数据类型

means = df.mean()
您可以使用以下方法获取该系列的索引值:

means.index
使用此选项对原始数据帧进行切片并减去平均值

df2 = df[means.index] - means

@Quang-Hoang是的,有一列每个人的名字。所有其他列都是数字。有办法解决这个问题吗?
@Quang-Hoang是的,有一列每个人的名字。所有其他列都是数字。有办法解决这个问题吗?