Turning table data into columns and counting by frequency

放肆的年华 提交于 2019-12-25 09:14:31

问题


I have a dataframe in the following form:

shape is 2326 x 1271

Column names are just serialized from 0-1269 while rows are categories that could repeat like "apple" in the example. The internal data points can represent anything (let's say they represent stores in this example) and I'm trying to convert them into columns and having the data points become the number of times that category shows up in that "store". Visually, here is the table I'm trying to get to:

Note that Apple shows up in AA and RR twice


回答1:


Use stack along with crosstab to compute the frequency counts:

Data:

index= ['Apple', 'Orange', 'Apple', 'Banana', 'Kiwi']
data = [['AA', 'DD', 'RR', ''], ['DD', 'PP', '', ''], 
        ['AA', 'RR', 'TT', 'SS'], ['EE', 'NN', '',''], ['NN', 'WW','', '']]
frame = pd.DataFrame(data, index, columns=np.arange(4))
frame

Operations:

df = frame.stack().reset_index(0, name='values')
df = pd.crosstab(df['level_0'], df['values']).drop('', axis=1).replace(0, '')
df.index.name=None; df.columns.name=None
df



来源:https://stackoverflow.com/questions/39898338/turning-table-data-into-columns-and-counting-by-frequency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!