Python Dataframe:使用列中的值创建新列
我已经搜索了好几本书和网站,但我找不到任何与我正在尝试做的事情完全匹配的东西。我想从数据框中创建逐项列表,并按如下方式重新配置数据:Python Dataframe:使用列中的值创建新列,python,pandas,Python,Pandas,我已经搜索了好几本书和网站,但我找不到任何与我正在尝试做的事情完全匹配的东西。我想从数据框中创建逐项列表,并按如下方式重新配置数据: 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
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非常陌生,有一个解决方案会很好,但了解我需要遵循的过程将是完美的
提前感谢使用pandas,您可以查询所有结果,例如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)
使用字符串的快速而肮脏的方法。根据需要自定义列命名
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
谢谢用户2589273…恐怕我的示例不够具体。这两列中的实际数据都由字符串组成,当我尝试这样做时,它会抱怨试图将字符串相乘。为了帮助我理解,第一行在做什么?请尝试df=df.convert\u objects convert\u numeric=True将字符串转换为数据帧的浮点数。或者更具体地说,df['A']=df['A']。convert\u objects convert\u numeric=True。我的第一行是创建一个空的零数组,因为我不知道你的值是连续的还是有间隙的…我也意识到我使用max可能是不正确的-现在编辑答案数据都是字符串,而不是以字符串表示的数字…更好的例子是:,我会给你看,但是格式没有正确显示,我不能发布图片,但是……想象一下,a列的数字是动物,B列的内容是马蹄、马长尾、猴子长尾等特征。我想在一行中收集动物后面的所有动物特征。非常感谢你的解释…这让我们更容易理解为什么。