转换/反转Pandas数据帧的最简单方法是什么?

2024-04-20 03:29:52 发布

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

我有以下熊猫数据帧:

Person     Item1      Item2     Item3     Item4
Adam       Apple      Eggs      Cookie
Alex       Chocolate  Orange    Eggs      Potato
Gina       Eggs       Apple     Orange    Milk

我想把它转换成:

^{pr2}$

在发布之前,我已经彻底搜索了我的查询,但是我没有找到任何匹配项(也许有更好的方法来重新表述我的问题)。如果这是重复的,我很抱歉,但是如果是,请告诉我这个问题之前的答案。在


Tags: 数据applecookieeggspotatopersonorangealex
2条回答

首先使用^{}重塑形状:

df = df.melt('Person', value_name='Item')
print (df)
   Person variable       Item
0    Adam    Item1      Apple
1    Alex    Item1  Chocolate
2    Gina    Item1       Eggs
3    Adam    Item2       Eggs
4    Alex    Item2     Orange
5    Gina    Item2      Apple
6    Adam    Item3     Cookie
7    Alex    Item3       Eggs
8    Gina    Item3     Orange
9    Adam    Item4        NaN
10   Alex    Item4     Potato
11   Gina    Item4       Milk

然后用^{}聚合lists的自定义函数,然后通过构造函数和^{}创建新的DataFrame,以计数列:

^{pr2}$

这不是你想要的,但是我不确定“换位”是否作为一个简单的函数存在。(顺便说一下,transpose,在线性代数之后,通常意味着将数据帧旋转90°)。在

# get items
items = []
for c in df.columns[1:]:
    items.extend(df[c].values)
items = list(set(items))
items.remove(None)

people = df.Person.values
counts = {}
for p in people:
    counts[p] = [1 if item in df[df['Person'] == p].values else 0 for item in items]

new = pd.DataFrame(counts, index=items)
new['Count'] = new.sum(axis=1)

输出:

^{pr2}$

编辑:和往常一样,jezrael给出了正确的答案,但是我修改了它以获得您想要的输出。对于初学者来说,这可能更容易理解。在

以“df”为例:

item_counts = {}
for item in items:
    counts = {}
    count = 0
    for p in people:
        if item in df[df['Person'] == p].values:
            count += 1
            counts['Person' + str(count)] = p
    counts['count'] = count
    item_counts[item] = counts

new = pd.DataFrame.from_dict(item_counts, orient='index')
new = new[['count', 'Person1', 'Person2', 'Person3']] # rearrange columns, optional

输出:

|           | count | Person1 | Person2 | Person3 |
|     -|   -|    -|    -|    -|
| Apple     | 2     | Adam    | Gina    | NaN     |
| Chocolate | 1     | Alex    | NaN     | NaN     |
| Cookie    | 1     | Adam    | NaN     | NaN     |
| Eggs      | 3     | Adam    | Alex    | Gina    |
| Milk      | 1     | Gina    | NaN     | NaN     |
| Orange    | 2     | Alex    | Gina    | NaN     |
| Potato    | 1     | Alex    | NaN     | NaN     |

相关问题 更多 >