如何转换python数据帧,以便将唯一的行值转换为列,并将另一列的值转换为它们的行

2024-09-28 21:55:34 发布

您现在位置:Python中文网/ 问答频道 /正文

摘要
我正在使用Python 2.7。我有一个包含所有分类变量的数据框,即数据类型为字符串。我想将一列的唯一行值转换为多列。此外,这些结果列的值必须具有来自另一列的相应值。为了详细描述,我提供了一个可复制的数据框架和预期输出,供您参考

需要转置的数据帧可以按如下方式创建:

import pandas as pd
codes = ['codeA','codeB', 'codeC']
variables = ['textA','textA','textB']
dataset = list(zip(codes,variables))
df = pd.DataFrame(data = dataset, columns=['codes','variables'])
df['string'] = 'string1'

需要转置的数据帧如下所示:

df
   codes variables   string
0  codeA     textA  string1
1  codeB     textA  string1
2  codeC     textB  string1

预期的最终输出应如下所示:

textA textB string
codeA       string1
codeB
      codeC string1

注:目的是换位。我不太关心空白空间是空值还是零值。eem>


Tags: 数据dfstring分类variablesdatasetcodescodec
1条回答
网友
1楼 · 发布于 2024-09-28 21:55:34

我不确定示例中的最后一列,因为它似乎与转换的其余部分不一致。无论如何,我认为使用pandasget_dummies函数转换变量列可能是一个很好的开始

import pandas as pd
codes = ['codeA','codeB', 'codeC']
variables = ['textA','textA','textB']
dataset = list(zip(codes,variables))
df = pd.DataFrame(data = dataset, columns=['codes','variables'])
df['string'] = 'string1'

df = pd.get_dummies(df, columns=['variables'])
df.variables_textA = df.codes.where(df.variables_textA.astype(bool),0)
df.variables_textB = df.codes.where(df.variables_textB.astype(bool),0)
columns = ['variables_textA', 'variables_textB','string']
df = df[columns]

Result

相关问题 更多 >