摘要
我正在使用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>
我不确定示例中的最后一列,因为它似乎与转换的其余部分不一致。无论如何,我认为使用pandas
get_dummies
函数转换变量列可能是一个很好的开始相关问题 更多 >
编程相关推荐