相关疑难解决方法(0)

Pandas列值到列?

我已经看到了将一个列/系列爆炸成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)

我觉得这应该是相对简单的事情,但是我现在一直在抨击我的头几个小时,随着卷积水平的提高,并没有成功.

python pandas

31
推荐指数
2
解决办法
2万
查看次数

将列值更改为pandas中的列标题

我有以下代码,它获取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)

python numpy pandas

11
推荐指数
1
解决办法
9729
查看次数

标签 统计

pandas ×2

python ×2

numpy ×1