【问题标题】:Pandas merging a Dataframe and a series熊猫合并数据框和系列
【发布时间】:2015-05-13 04:51:29
【问题描述】:

我有两个熊猫数据框: 一个包含客户号码的匿名散列(这里为简单起见,是数字 0-19 的散列)

import pandas as pd
import numpy as np
from hashlib import sha1

df_customers = pd.DataFrame( [ sha1(i).hexdigest() for i in     np.arange(20)] )
df_customers.columns = ["customer"]

现在我有第二个表(DataFrame),其中包含 200 次出现的客户从 20 种不同种类的水果中挑选:

fruit = ["apple", "banana", "peach", "plum", "orange", "cumquat", "raspberry", "lemon", "rubarb", "pineapple"]
pd.DataFrame( np.c_[ np.array([ sha1(i).hexdigest() for i in np.random.randint(0,20,200) ]),
          np.array([ fruit[i]  for i in np.random.randint(0,len(fruit),200) ]) ],
         columns=("customer_id","fruit")
         )

现在我想在客户 DataFrame 中添加一列,指示食用水果的种类——即每位客户食用的不同水果的数量。为此我做到了:

variety = df_eating.groupby("customer_id")["fruit"].apply( lambda x: len(np.unique(x)))

这给了我一个“系列”。现在我觉得应该有一种直接的方式将其添加回 df_customer,尊重 customer_id 但在这里我很卡住:

pd_customer["variety"] = variety

不尊重客户 ID 并为每个值提供 NaN

还有像pd.merge() 这样的函数,其中有一个选项可以合并“on”某事并没有达到我想要的效果。

【问题讨论】:

  • 我已经用 numpy 做了很多,但我是 pandas 的新手,所以任何关于如何改进我上面的代码的 cmets 也非常受欢迎

标签: python pandas


【解决方案1】:

如果我明白你想要什么,那么你可以致电map 并通过系列:

In [36]:

df_customers['variety'] = df_customers['customer'].map(variety)
df_customers
Out[36]:
                                    customer  variety
0   9069ca78e7450a285173431b3e52c5c25299e473        7
1   3c585604e87f855973731fea83e21fab9392d2fc        9
2   0aaf76f425c6e0f43a36197de768e67d9e035abb        6
3   8e146c3c4e33449f95a49679795f74f7ae19ecc1        6
4   d6459ab29c7b9a9fbf0c7c15fa35faa30fbf8cc6        7
5   ddaf0ed54dfc227ce677b5c2b44e3edee7c7db77        5
6   8098e7dfb09adba3bf783794ba0db81985a814d7        6
7   2f086fc767a0dac59a38c67f409b4f74a1eab39f        8
8   a454ca483b4a66b83826d061be2859dd79ff0d6c        7
9   9db063f3b5e0adfd0d29a03db0a1c207b3740a94        6
10  eb408ddc4fa484e6befdf5954e56a2198c7a9fab        8
11  94312fc592ee3f323b3f9d8612737c507ec7f6c3        5
12  f3a56292ca640b843071c9a143404cea014f4d5c        9
13  b1197c208248d0f7ffb3e322d5ec187441dc1b26        7
14  f143c36fc53bfde11a8d122249aced46c43cc2e2        7
15  aefa2f5632d36978838bff3aabcef5ee01395729        5
16  5497b0911b3f5772723def3b360a2e654327c19b        6
17  498bcbf6cbffcc8dd2623f388d81f44cfad1014d        5
18  96760d655a51e69d67d32a5f18c23c9bfe0576cf        5
19  fe5aa6438ae9b661b033b91e9c679ad2898cbfd4        6

关于优化您的代码,您可以替换这一行:

variety = df_eating.groupby("customer_id")["fruit"].apply( lambda x: len(np.unique(x)))

与等价物:

variety = df_eating.groupby("customer_id")["fruit"].nunique()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2019-09-27
    • 2016-10-31
    • 2020-06-03
    • 2021-06-30
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多