2015-09-09 53 views
4

的多个结果。如果我有一个DataFrame其中每一行都是一个个体,每一列单独的属性,我怎么能得到一个新的DataFrame每个单独映射到多个结果如何?为每个行(一到多)与熊猫

我试过用DataFrame.apply()这样做,这似乎是最直观的 - 但它给出了例外,如下例所示。添加broadcast=Falsereduce=False没有帮助。

下面是一个简单的例子,很明显,但考虑到每一行都映射到多行的任何场景。处理这个问题的最好方法是什么?实际上,每一行都可以映射到不同数量的结果。这基本上是计算一对多的关系。

:我有一个DataFrame数据集具有以下结构,我想,每一个人,拿到3个即将到来的生日(简单的例子,我知道)。所以,从:

+---+-------+------------+ 
| | name | birthdate | 
+---+-------+------------+ 
| 1 | John | 1990-01-01 | 
| 2 | Jane | 1957-04-03 | 
| 3 | Max | 1987-02-03 | 
| 4 | David | 1964-02-12 | 
+---+-------+------------+ 

喜欢的东西:

+-------+------------+ 
| name | birthday | 
+-------+------------+ 
| John | 2016-01-01 | 
| John | 2017-01-01 | 
| John | 2018-01-01 | 
| Jane | 2016-04-03 | 
| Jane | 2017-04-03 | 
| Jane | 2018-04-03 | 
| Max | 2016-02-03 | 
| Max | 2017-02-03 | 
| Max | 2018-02-03 | 
| David | 2016-02-12 | 
| David | 2017-02-12 | 
| David | 2018-02-12 | 
+-------+------------+ 

直觉上,我会尝试这样的事情:

def get_birthdays(person): 
    birthdays = [] 
    for year in range(2016, 2019): 
     birthdays.append({ 
      'name': person.name, 
      'birthday': person.birthdate.replace(year=year) 
     }) 

    return pd.DataFrame(birthdays) 

# with data as my original DataFrame 
data.apply(get_birthdays, axis=1) 

然而,这引起了:

ValueError: could not broadcast input array from shape (3,2) into shape (3) 

During handling of the above exception, another exception occurred: 

[...] 

ValueError: cannot copy sequence with size 2 to array axis with dimension 3 

回答

4

groupby版本o ˚Fapply支持DataFrame作为方式返回值,你打算:

import pandas as pd 
from datetime import datetime 

df = pd.DataFrame({ 
    'name': ['John', 'Jane', 'Max', 'David'], 
    'birthdate': [datetime(1990,1,1), datetime(1957,4,3), datetime(1987,2,3), datetime(1964,2,12)], 
}) 

def get_birthdays(df_x): 
    d = {'name': [], 'birthday': []} 
    name = df_x.iloc[0]['name'] 
    original = df_x.iloc[0]['birthdate'] 
    for year in range(2016, 2019): 
     d['name'].append(name) 
     d['birthday'].append(original.replace(year=year)) 
    return pd.DataFrame(d) 

print df.groupby('name', group_keys=False).apply(get_birthdays).reset_index(drop=True) 

输出:

 birthday name 
0 2016-02-12 David 
1 2017-02-12 David 
2 2018-02-12 David 
3 2016-04-03 Jane 
4 2017-04-03 Jane 
5 2018-04-03 Jane 
6 2016-01-01 John 
7 2017-01-01 John 
8 2018-01-01 John 
9 2016-02-03 Max 
10 2017-02-03 Max 
11 2018-02-03 Max 
+0

大,谢谢!你是否有任何理由将列表中的字典列表传递给'pd.DataFrame'? – vicvicvic

+1

在这种情况下,这只是个人偏好。当列表很长的时候,列表字典更有效率;然而,这里的列表很短,因此在内存开销方面,您的字典列表方法可能会更好。 –