Python Pandas Dataframe:使用列中的值创建新列

问题描述:

我搜索了几本书籍和网站,找不到与我想要做的事情完全相符的内容。我想从一个数据帧创建细目清单和重新配置数据,像这样:Python Pandas Dataframe:使用列中的值创建新列

 A  B    A  B  C  D 
0  1  aa   0 1  aa 
1  2  bb   1 2  bb 
2  3  bb   2 3  bb aa 
3  3  aa  --\ 3 4  aa bb dd 
4  4  aa  --/ 4 5  cc 
5  4  bb 
6  4  dd 
7  5  cc 

我和分组实验,堆垛,拆垛等,但没有,我已经尝试产生了预期的结果。如果它不是很明显,我对Python非常陌生,解决方案会很棒,但对我需要遵循的过程的理解是完美的。

在此先感谢

使用熊猫可以查询所有结果,例如其中A = 4。

一个粗糙但工作的方法是遍历各种索引值,并将所有“喜欢”结果收集到一个numpy数组中,并将其转换为新的数据框。

伪代码来说明我的例子: (将需要重写实际工作)

l= [0]*df['A'].max() 
for item in xrange(df['A'].max()): 
    l[item] = df.loc[df['A'].isin(item)] 

df = pd.DataFrame(l) 
# or something of the sort 

我希望帮助。从评论

更新:

animal_list=[] 

for animal in ['cat','dog'...]: 
    newdf=df[[x.is('%s'%animal) for x in df['A']]] 

    body=[animal]  
    for item in newdf['B'] 
     body.append(item) 

    animal_list.append(body) 

df=pandas.DataFrame(animal_list) 
+0

感谢user2589273 ......我怕我是不是在我的例子不够具体。两列中的实际数据都是由字符串组成的,当我尝试这些时,它会抱怨尝试乘以字符串。为了帮助我理解,第一行是干什么的? – Velcro 2015-02-05 20:45:19

+0

尝试df = df.convert_objects(convert_numeric = True)将字符串转换为数据框的浮点数。或者更具体地说df ['A'] = df ['A']。convert_objects(convert_numeric = True)。我的第一行是创建一个空的零数组,因为我不知道你的值是连续的还是有差距... – user2589273 2015-02-05 23:57:57

+0

我也意识到我对max的使用可能是不正确的 - 现在编辑答案 – user2589273 2015-02-05 23:58:24

一个快速和肮脏的方法,将与字符串的工作。根据需要自定义列命名。

data = {'A': [1, 2, 3, 3, 4, 4, 4, 5], 
     'B': ['aa', 'bb', 'bb', 'aa', 'aa', 'bb', 'dd', 'cc']} 
df = pd.DataFrame(data) 

maxlen = df.A.value_counts().values[0] # this helps with creating 
            # lists of same size 

newdata = {} 
for n, gdf in df.groupby('A'): 
    newdata[n]= list(gdf.B.values) + [''] * (maxlen - len(gdf.B)) 

# recreate DF with Col 'A' as index; experiment with other orientations 
newdf = pd.DataFrame.from_dict(newdict, orient='index') 

# customize this section 
newdf.columns = list('BCD') 
newdf['A'] = newdf.index 
newdf.index = range(len(newdf)) 
newdf = newdf.reindex_axis(list('ABCD'), axis=1) # to set the desired order 

print newdf 

结果是:

 
    A B C D 
0 1 aa   
1 2 bb   
2 3 bb aa  
3 4 aa bb dd 
4 5 cc