将预定义的数字分配给数据框中的列行值

问题描述 投票:2回答:3

假设我有一个数据帧

   C                 D
agree           Average
agree           agree
strongly agree  disagree
disagree        agree

我想要做的是为这样的C列值分配数字?

 C  D
 1  3
 1  1
 2  0
 0  1

我可以使用map作为单列,但如果有多列,我如何将值更改为数字而无需为每个列单独写入(我知道我可以使用for循环,但问题是我将如何在此处应用它)

有人知道怎么做吗?

我试图使用for循环

def assignNumbers(df):


for i in df:

    dftest= df[i].map({'Average':3, 'Agree':1, 'Disagree':0, 'Strongly Agree':2})

return dftest
python pandas loops for-loop dataframe
3个回答
0
投票

一种方法是

df.replace({'Average': 3, 'agree': 1, 'disagree': 0, 'strongly agree': 2})

1
投票

使用pd.factorize作为通用解决方案(例如,如果您事先不知道有多少类别)。

pd.DataFrame(pd.factorize(df.values.T.reshape(-1,))[0].reshape(df.shape[1], -1), index=df.columns).T

    C   D
0   0   3
1   0   0
2   1   2
3   2   0

0
投票

您可以使用类别和cat.codes

df.unstack().astype('category').cat.codes.unstack(0)

   C  D
0  1  0
1  1  1
2  3  2
3  2  1

如果您确实希望匹配输出,而不仅仅为每个变量分配唯一值,则可以创建CategoricalDtype并定义顺序。

from pandas.api.types import CategoricalDtype
cat = CategoricalDtype(
    categories=['disagree', 'agree', 'strongly agree', 'Average'], ordered=True
)

df.stack().astype(cat).cat.codes.unstack(1)

   C  D
0  1  3
1  1  1
2  2  0
3  0  1
© www.soinside.com 2019 - 2024. All rights reserved.