我已经看到了将一个列/系列爆炸成Pandas数据帧的多个列的主题的一些变化,但我一直在尝试做一些事情而不是真正成功地使用现有的方法.
给定一个像这样的DataFrame:
key val
id
2 foo oranges
2 bar bananas
2 baz apples
3 foo grapes
3 bar kiwis
Run Code Online (Sandbox Code Playgroud)
我想将key系列中的项目转换为列,并将val值作为值,如下所示:
foo bar baz
id
2 oranges bananas apples
3 grapes kiwis NaN
Run Code Online (Sandbox Code Playgroud)
我觉得这应该是相对简单的事情,但是我现在一直在抨击我的头几个小时,随着卷积水平的提高,并没有成功.
我有以下代码,它获取pandas数据帧的一列中的值,并使它们成为新数据框的列.数据帧第一列中的值将成为新数据帧的索引.
从某种意义上说,我想将邻接列表转换为邻接矩阵.这是迄今为止的代码:
import pandas as pa
print "Original Data Frame"
# Create a dataframe
oldcols = {'col1':['a','a','b','b'], 'col2':['c','d','c','d'], 'col3':[1,2,3,4]}
a = pa.DataFrame(oldcols)
print a
# The columns of the new data frame will be the values in col2 of the original
newcols = list(set(oldcols['col2']))
rows = list(set(oldcols['col1']))
# Create the new data matrix
data = np.zeros((len(rows), len(newcols)))
# Iterate over each row and fill in the new matrix
for row in zip(a['col1'], a['col2'], a['col3']):
rowindex = rows.index(row[0])
colindex = newcols.index(row[1]) …Run Code Online (Sandbox Code Playgroud)