一個快速和骯髒的方法,將與字符串的工作。根據需要自定義列命名。
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
感謝user2589273 ......我怕我是不是在我的例子不夠具體。兩列中的實際數據都是由字符串組成的,當我嘗試這些時,它會抱怨嘗試乘以字符串。爲了幫助我理解,第一行是幹什麼的? – Velcro 2015-02-05 20:45:19
嘗試df = df.convert_objects(convert_numeric = True)將字符串轉換爲數據框的浮點數。或者更具體地說df ['A'] = df ['A']。convert_objects(convert_numeric = True)。我的第一行是創建一個空的零數組,因爲我不知道你的值是連續的還是有差距... – user2589273 2015-02-05 23:57:57
我也意識到我對max的使用可能是不正確的 - 現在編輯答案 – user2589273 2015-02-05 23:58:24