[英]Iterate through rows and columns, python
請你幫我破解計算嗎?
我有下表:
我需要做的是將預期頻率計算為(行總數*總數)/總計
我假設我需要遍歷行和列。 我試過這樣做:
for i, row in df_dropped.iterrows():
for j, column in row.iteritems():
data[row][column] = df_dropped.iloc[i, 3] * df_dropped.iloc[2, j]
出現錯誤:基於位置的索引只能有[整數,整數切片(START點為INCLUDED,END point為EXCLUDED),listlike of integer,boolean array]類型
我究竟做錯了什么?
使用numpy.outer
作為最后一列和最后一行的外積並除以
loc
選擇的標量為numpy數組:
t = df.loc['col_sum', 'row_sum']
arr = np.outer(df['row_sum'], df.loc['col_sum']) / t
然后通過contructor創建DataFrame,使用索引刪除最后一列ans行:
df1 = pd.DataFrame(arr[:-1, :-1],
columns=df.columns[:-1],
index=df.index[:-1]).add_prefix('exp_')
print (df1)
exp_satisfied exp_neutral exp_dissatisfied
0 24.605263 20.842105 9.552632
1 145.394737 123.157895 56.447368
獲取新列名稱:
cols = [item for x in df.columns[:-1] for item in (x, 'exp_' + x)]
print (cols)
['satisfied', 'exp_satisfied', 'neutral', 'exp_neutral', 'dissatisfied', 'exp_dissatisfied']
df = pd.concat([df.iloc[:-1, :-1], df1], axis=1).reindex(columns=cols)
print (df)
satisfied exp_satisfied neutral exp_neutral dissatisfied \
0 30 24.605263 17 20.842105 8
1 140 145.394737 127 123.157895 58
exp_dissatisfied
0 9.552632
1 56.447368
Jezrael給出了一個很好的答案,你使用numpy和pandas計算預期的頻率。 您還可以使用python統計庫statsmodels來計算這些類型的統計信息。
例如,要計算預期頻率表,您可以:
import statsmodels.api as sm
expected_values = sm.stats.Table(df).fittedvalues
更多信息: statsmodels列聯表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.