我有一个小循环,它给了我n个片段的数据列表。下面是代码:
for df_grp in df.groupby(['Segment']):
grp_ci = 1.96 * np.std(grp['Conversion_Percentage'])/math.sqrt(len(grp['Conversion_Percentage']))
grp_cvr = grp['Conversion_Percentage'].iloc[-1]
grp_ci95plus = grp_cvr + grp_ci
grp_ci95minus = grp_cvr - grp_ci
stat = (grp_ci,grp_cvr,grp_ci95plus,grp_ci95minus)
print(stat)
我基本上想要这4个统计输出,我在这里得到一个列表,如下所示:
(0.7443617976588611, 8.349514563106796, 9.093876360765657, 7.605152765447935)
(0.5279035518807871, 7.9468622035996574, 8.474765755480444, 7.418958651718871)
这是按段A分组的样本数据,其他段也是如此。这个特定的子集给出了我正在计算的4个统计值:
days user Conversion_Percentage
0 0.0 618 2.942577
1 1.0 638 3.037806
2 2.0 662 3.152081
3 3.0 686 3.266356
4 4.0 726 3.456814
5 5.0 835 3.975812
6 6.0 915 4.356728
7 7.0 971 4.623369
8 8.0 1004 4.780497
但是我希望它以表格的形式出现。最重要的是,我想要得到行和列标头。我尝试将列表转换为数据框架:
array = (grp_ci,grp_cvr,grp_ci95plus,grp_ci95minus)
index_values = ['grp']
column_values = ['ci','cvr','ci95plus','ci95minus']
stat= pd.DataFrame(data = array, index = index_values, columns = column_values)
print(stat)
但是它给了我错误:
AttributeError: module 'pandas' has no attribute 'Dataframe'
我已经检查了我没有使用包名称命名任何文件或脚本,但仍然无法理解此错误。我也多次更改我的数据帧代码,看看我是否写错了代码,但没有运气。我的grp是段是我想要的东西在行和作为4个统计数据计算,我想要他们在列头。如果它是在表格的形式,但至少我需要标题。这将是更好的,如果我有很多段值,我将所有的段打印在每一行的4列。像这样:
ci cvr ci95plus ci95minus
A 0.7443617976588611 8.349514563106796 9.093876360765657 7.605152765447935
B 0.5279035518807871 7.9468622035996574 8.474765755480444 7.418958651718871
编辑:我将Dataframe更改为Dataframe。很抱歉。现在我得到错误:ValueError:传递值的形状是(4,1),索引暗示(1,4)
我假设您正在使用列表。你可以试试这个
import pandas
import numpy
DATA = {'days': [0.0 ,1.0 ,2.0 ,3.0 ,4.0 ,5.0 ,6.0 ,7.0 ,8.0],
'user': [618 ,638 ,662 ,686 ,726 ,835 ,915 ,971 ,1004],
'Conversion_Percentage': [2.942577 ,3.037806 ,3.152081
,3.266356 ,3.456814 ,3.975812 ,4.356728 ,4.623369 ,4.780497]}
# You need to adjust the calculation in the function to suit what you want to achieve.
def conversion(x):
grp_cvr= 1.96 * np.std(df['Conversion_Percentage'])/math.sqrt(len(df['Conversion_Percentage']))
grp_ci= x #adjust to fit your calculation
grp_ci95plus = grp_cvr + grp_ci
grp_ci95minus = grp_cvr - grp_ci
return grp_ci,grp_cvr,grp_ci95plus,grp_ci95minus
#columns and index mapping
index2 = {0: 'A', 1: 'b', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I'}
col= ['ci','cvr','ci95plus','ci95minus']
new_columns=dict(zip(range(len(col)),col))
df= pd.DataFrame(DATA)
new =(df['Conversion_Percentage'].apply(conversion)
.apply(pd.Series))
index2 = {0: 'A', 1: 'b', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I'}
new_columns=dict(zip(new.columns,['ci','cvr','ci95plus','ci95minus']))
new.columns=new_columns