我有一个 pandas 表 df:
course
ID
1 physics101
1 astronomy
2 maths
2 another
我想导出一个具有以下结果的表:
physics101 astronomy maths another
ID
1 True True False False
2 False False True True
这是什么样的操作?
(df 的元素是一组已定义的类)
最佳答案
您可以使用crosstab()
:
import pandas as pd
from StringIO import StringIO
data = StringIO("""ID course
1 physics101
1 astronomy
2 maths
2 another""")
df = pd.read_csv(data, delim_whitespace=True)
pd.crosstab(df.ID, df.course) > 0
输出:
course another astronomy maths physics101
ID
1 False True False True
2 True False True False
关于pandas - 在 Pandas 行中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010077/