我需要处理来自大数据csv的地理和统计数据。它包含来自地理行政和地统计学的数据。市,地理位置,地统计基本划分和区块构成等级指标。
我必须为地理索引中数据的最大值为每个元素创建一个新列[' data2'],并将每个块值除以该值。对于每个索引级别,索引级别值必须与0不同,因为0索引级别值会计算计算中未使用的其他类型的信息。
data1 data2
mun loc geo block
1 0 0 0 20 20
1 1 0 0 10 10
1 1 1 0 10 10
1 1 1 1 3 3/4
1 1 1 2 4 4/4
1 1 2 0 30 30
1 1 2 1 1 1/3
1 1 2 2 3 3/3
1 2 1 1 10 10/12
1 2 1 2 12 12/12
2 1 1 1 123 123/123
2 1 1 2 7 7/123
2 1 2 1 6 6/6
2 1 2 2 1 1/6
有什么想法吗?我尝试过for循环,使用reset_index()转换列中的索引并按列和行值迭代,但计算是永远的,我认为这不是执行此类操作的正确方法。
另外,如果我想得到这样的面具,那么我可以将计算运行到每个级别。
mun loc geo block
1 0 0 0 False
1 1 0 0 False
1 1 1 0 True
1 1 1 1 False
1 1 1 2 False
1 1 2 0 True
1 1 2 1 False
1 1 2 2 False
mun loc geo block
1 0 0 0 False
1 1 0 0 True
1 1 1 0 False
1 1 1 1 False
1 1 1 2 False
1 2 0 0 True
1 2 2 0 False
1 2 2 1 False
mun loc geo block
1 0 0 0 True
1 1 0 0 False
1 1 1 0 False
1 1 1 1 False
1 1 1 2 False
2 0 0 0 True
2 1 1 0 False
2 1 2 1 False
答案 0 :(得分:1)
您可以先从MultiIndex
创建mask
,与0
进行比较,然后至少检查一个True
(至少一个0
){{3 }}:
mask = (pd.DataFrame(df.index.values.tolist(), index=df.index) == 0).any(axis=1)
print (mask)
mun loc geo block
1 0 0 0 True
1 0 0 True
1 0 True
1 False
2 False
2 0 True
1 False
2 False
2 1 1 False
2 False
2 1 1 1 False
2 False
2 1 False
2 False
dtype: bool
然后按照any
每个第一,第二和第三个索引获取max
个值,但在按groupby
过滤之前,True
中只有mask
的值:
df1 = df.ix[~mask, 'data1'].groupby(level=['mun','loc','geo']).max()
print (df1)
mun loc geo
1 1 1 4
2 3
2 1 12
2 1 1 123
2 6
然后df1
df.index
按Multiindex
移除mask
的最后一级boolean indexing
,reindex
值,其中1
没有变化(还必须删除最后一级)和df1 = df1.reindex(df.reset_index(level=3, drop=True).index)
.mask(mask.reset_index(level=3, drop=True)).fillna(1)
print (df1)
Name: data1, dtype: int64
mun loc geo
1 0 0 1.0
1 0 1.0
1 1.0
1 4.0
1 4.0
2 1.0
2 3.0
2 3.0
2 1 12.0
1 12.0
2 1 1 123.0
1 123.0
2 6.0
2 6.0
Name: data1, dtype: float64
print (df['data1'].div(df1.values,axis=0))
mun loc geo block
1 0 0 0 20.000000
1 0 0 10.000000
1 0 10.000000
1 0.750000
2 1.000000
2 0 30.000000
1 0.333333
2 1.000000
2 1 1 0.833333
2 1.000000
2 1 1 1 1.000000
2 0.056911
2 1 1.000000
2 0.166667
dtype: float64
,因为除以返回相同的值。
CREATE PROCEDURE usp_getStudentsAndClasses
@ClassName varchar(50)
, @IsActive bit
AS
BEGIN
--First select is first table
SELECT *
FROM Students
--Second select is second table, etc.
SELECT *
FROM Classes
--Third table...
--Can be more complex, as long as there is a result set
SELECT s.FirstName
, s.LastName
FROM Students s
JOIN StudentSeating ss
ON s.StudentID = ss.StudentID
JOIN Classes c
ON c.ClassID = ss.ClassID
WHERE s.IsActive = @IsActive
AND c.Name = @ClassName
END
最后除以reset_index
:
public DataSet GetDataSet(SqlConnection connection, string storedProcName, params SqlParameter[] parameters)
{
var command = new SqlCommand(storedProcName, connection) { CommandType = CommandType.StoredProcedure };
command.Parameters.AddRange(parameters);
var result = new DataSet();
var dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(result);
return result;
}