【发布时间】:2013-11-13 21:46:48
【问题描述】:
我收到此代码以将数据分组为直方图类型数据。我一直在尝试理解这个 pandas 脚本中的代码,以便对其进行编辑、操作和复制。对于我理解的部分,我有 cmets。
代码
import numpy as np
import pandas as pd
column_names = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6',
'col7', 'col8', 'col9', 'col10', 'col11'] #names to be used as column labels. If no names are specified then columns can be refereed to by number eg. df[0], df[1] etc.
df = pd.read_csv('data.csv', header=None, names=column_names) #header= None means there are no column headings in the csv file
df.ix[df.col11 == 'x', 'col11']=-0.08 #trick so that 'x' rows will be grouped into a category >-0.1 and <= -0.05. This will allow all of col11 to be treated as a numbers
bins = np.arange(-0.1, 1.0, 0.05) #bins to put col11 values in. >-0.1 and <=-0.05 will be our special 'x' rows, >-0.05 and <=0 will capture all the '0' values.
labels = np.array(['%s:%s' % (x, y) for x, y in zip(bins[:-1], bins[1:])]) #create labels for the bins
labels[0] = 'x' #change first bin label to 'x'
labels[1] = '0' #change second bin label to '0'
df['col11'] = df['col11'].astype(float) #convert col11 to numbers so we can do math on them
df['bin'] = pd.cut(df['col11'], bins=bins, labels=False) # make another column 'bins' and put in an integer representing what bin the number falls into.Later we'll map the integer to the bin label
df.set_index('bin', inplace=True, drop=False, append=False) #groupby is meant to run faster with an index
def count_ones(x):
"""aggregate function to count values that equal 1"""
return np.sum(x==1)
dfg = df[['bin','col7','col11']].groupby('bin').agg({'col11': [np.mean], 'col7': [count_ones, len]})
dfg.index = labels[dfg.index]
dfg.ix['x',('col11', 'mean')]='N/A'
print(dfg)
dfg.to_csv('new.csv')
我真正难以理解的部分在这个部分:
def count_ones(x):
"""aggregate function to count values that equal 1"""
return np.sum(x==1)
dfg = df[['bin','col7','col11']].groupby('bin').agg({'col11': [np.mean], 'col7': [count_ones, len]})
dfg.index = labels[dfg.index]
dfg.ix['x',('col11', 'mean')]='N/A'
print(dfg)
dfg.to_csv('new.csv')
如果有人能够评论这个脚本,我将不胜感激。也可以随意更正或添加到我的 cmets 中(这些是我到目前为止所假设的,它们可能不正确)。我希望这对 SOF 来说不是太离题。我很乐意为任何可以帮助我的用户提供 50 点奖励。
【问题讨论】:
-
首先阅读 agg 函数文档
-
谢谢,到目前为止,我一直在看熊猫教程视频。
-
我相信这也是他所指的文档。 pandas.pydata.org/pandas-docs/dev/groupby.html 恐怕我无法为 cmets 提供帮助,这段代码暂时超出了我的能力范围。
-
@Boud 原始 cmets 中有什么不正确的吗? (以防万一我被领着欢快的舞蹈)
-
感谢@GTPE 现在提供该文档。
标签: python python-2.7 numpy pandas comments