最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python清洗問卷數(shù)據(jù)的實戰(zhàn)方法

 更新時間:2026年07月09日 09:38:42   作者:nothing&nowhere  
做問卷研究的人都知道,回收數(shù)據(jù)里一定有垃圾,直線作答、秒填、規(guī)律選擇、前后矛盾……這些數(shù)據(jù)如果不清理掉,分析結果會被嚴重污染,信效度也過不了關,這篇教程教你用 Python 從零寫一套問卷數(shù)據(jù)清洗流程,需要的朋友可以參考下

引言

做問卷研究的人都知道,回收數(shù)據(jù)里一定有垃圾。直線作答、秒填、規(guī)律選擇、前后矛盾……這些數(shù)據(jù)如果不清理掉,分析結果會被嚴重污染,信效度也過不了關。

這篇教程教你用 Python 從零寫一套問卷數(shù)據(jù)清洗流程,覆蓋最常見的無效樣本類型。

適用場景: 畢業(yè)論文問卷、學術調研、市場研究、用戶滿意度調查等。

準備工作

你需要:

  • Python 3.8+
  • pandas、numpy、matplotlib
  • 一份導出為 CSV 或 Excel 的問卷數(shù)據(jù)
pip install pandas numpy matplotlib openpyxl

問卷星導出的數(shù)據(jù)一般是這個結構(每行一份問卷,每列一個題目):

序號提交時間Q1Q2Q3Q4Q5
12025-03-15 14:30:02滿意一般滿意滿意滿意
22025-03-15 14:30:05非常不滿意非常不滿意非常不滿意非常不滿意非常不滿意

不用多說,第 2 行明顯是垃圾數(shù)據(jù)。但實際場景里無效樣本通常沒這么明顯。

第一步:加載數(shù)據(jù)

import pandas as pd
import numpy as np

# 問卷星導出通常是 Excel 或 CSV
df = pd.read_excel('問卷數(shù)據(jù).xlsx')
# 或
# df = pd.read_csv('問卷數(shù)據(jù).csv')

print(f"原始數(shù)據(jù)量: {len(df)} 份")
print(df.head())

通常問卷星導出的列名比較亂,先整理一下:

# 找出題目列(通常包含 "Q" 或題號)
question_cols = [c for c in df.columns if c.startswith('Q') or '第' in str(c)]
time_col = [c for c in df.columns if '時間' in str(c) or 'time' in str(c).lower()]

print(f"題目列: {question_cols}")
print(f"時間列: {time_col}")

第二步:檢測直線作答(Straight-lining)

直線作答是最常見的無效模式——所有題目選了同一個選項。

def detect_straight_lining(df, question_cols):
    """檢測所有題目答案完全一致的樣本"""
    invalid_indices = []

    for idx, row in df.iterrows():
        answers = row[question_cols].dropna().tolist()
        if len(answers) < 3:
            continue
        # 如果所有答案都相同
        if len(set(answers)) == 1:
            invalid_indices.append(idx)

    return set(invalid_indices)

straight_lining = detect_straight_lining(df, question_cols)
print(f"直線作答: {len(straight_lining)} 份")

但直線作答也有誤判的情況。比如 5 道題都是"滿意",可能是真實感受。所以加一個更嚴格的判斷——不要求完全一致,而是 80% 以上選項相同

def detect_near_straight_lining(df, question_cols, threshold=0.8):
    """檢測接近直線作答(超過 threshold 比例的答案相同)"""
    invalid_indices = []

    for idx, row in df.iterrows():
        answers = row[question_cols].dropna().tolist()
        if len(answers) < 3:
            continue
        # 找出現(xiàn)最多的答案
        from collections import Counter
        counts = Counter(answers)
        most_common_ratio = counts.most_common(1)[0][1] / len(answers)
        if most_common_ratio >= threshold:
            invalid_indices.append(idx)

    return set(invalid_indices)

near_straight = detect_near_straight_lining(df, question_cols)
print(f"接近直線作答: {len(near_straight)} 份")

第三步:檢測秒填(Speeders)

如果有人在 10 秒內"填完"了一份 20 題的問卷,基本可以確定是無效數(shù)據(jù)。

def detect_speeders(df, time_col, min_seconds=10):
    """檢測提交時間異常短的樣本"""
    if not time_col:
        return set()

    time_data = pd.to_datetime(df[time_col[0]])

    # 按時間排序,計算相鄰提交的時間差
    time_sorted = time_data.sort_values()
    time_diffs = time_sorted.diff().dt.total_seconds()

    # 方法1:如果數(shù)據(jù)里有"答題時長"字段,直接用
    duration_col = [c for c in df.columns if '時長' in str(c) or '用時' in str(c)]
    if duration_col:
        durations = pd.to_numeric(df[duration_col[0]], errors='coerce')
        speeder_indices = df[durations < min_seconds].index
        return set(speeder_indices)

    # 方法2:沒有時長字段,用提交間隔估算(粗略)
    return set()

speeders = detect_speeders(df, time_col, min_seconds=15)
print(f"秒填樣本: {len(speeders)} 份")

如果問卷星導出的數(shù)據(jù)里包含答題時長列,直接按閾值過濾就行。一般規(guī)則:

  • 10 題以內的問卷:< 10 秒視為秒填
  • 10-20 題:< 20 秒視為秒填
  • 20 題以上:< 30 秒視為秒填

第四步:檢測規(guī)律作答(Pattern Response)

有些人會按規(guī)律選:1-2-3-4-5-1-2-3-4-5,或者 5-4-3-2-1-5-4-3-2-1。

def detect_pattern_response(df, question_cols):
    """檢測規(guī)律性作答(遞增、遞減、交替等模式)"""
    invalid_indices = []

    for idx, row in df.iterrows():
        answers = row[question_cols].dropna().tolist()
        if len(answers) < 5:
            continue

        # 把文字選項轉為數(shù)字(如果是文字的話需要先編碼)
        try:
            numeric = pd.to_numeric(answers)
        except:
            # 文字選項,檢查是否完全交替(A-B-A-B)
            if len(answers) >= 6:
                half = len(answers) // 2
                first_half = answers[:half]
                second_half = answers[half:half*2]
                if first_half == second_half:
                    invalid_indices.append(idx)
            continue

        # 檢測嚴格遞增/遞減
        diffs = np.diff(numeric)
        if np.all(diffs == diffs[0]) and diffs[0] != 0:
            invalid_indices.append(idx)
            continue

        # 檢測交替模式(1-3-1-3-1-3)
        if len(numeric) >= 6:
            even_vals = numeric[::2]
            odd_vals = numeric[1::2]
            if len(set(even_vals)) == 1 and len(set(odd_vals)) == 1:
                invalid_indices.append(idx)

    return set(invalid_indices)

patterns = detect_pattern_response(df, question_cols)
print(f"規(guī)律作答: {len(patterns)} 份")

第五步:檢測矛盾回答

如果 Q1 問"您是否使用過本產品"選了"否",但 Q5 問"您對產品的哪些功能最滿意"卻填了具體內容,這就是矛盾回答。

def detect_contradictions(df, filter_col, filter_value, check_col):
    """
    檢測邏輯矛盾
    filter_col: 篩選題列(如"是否使用過")
    filter_value: 篩選值(如"否")
    check_col: 應該為空的列(如后續(xù)滿意度題)
    """
    mask = df[filter_col] == filter_value
    should_be_empty = df.loc[mask, check_col]
    # 篩選了"否"的人,后續(xù)題不應該有內容
    contradictions = should_be_empty[should_be_empty.notna() & (should_be_empty != '')]
    return set(contradictions.index)

# 示例:選了"沒使用過"但后面題有回答
# contradictions = detect_contradictions(df, 'Q1', '否', 'Q5')

這一步需要根據(jù)具體問卷邏輯來寫,沒有通用模板。

第六步:檢測異常值(統(tǒng)計方法)

對于量表題(1-5 分或 1-7 分),可以用統(tǒng)計方法檢測異常樣本。

def detect_outliers_zscore(df, question_cols, threshold=3.0):
    """用 Z-score 檢測每個樣本的總分異常"""
    # 把題目轉為數(shù)值
    numeric_df = df[question_cols].apply(pd.to_numeric, errors='coerce')
    row_means = numeric_df.mean(axis=1)

    z_scores = (row_means - row_means.mean()) / row_means.std()
    outlier_indices = df[abs(z_scores) > threshold].index

    return set(outlier_indices)

outliers = detect_outliers_zscore(df, question_cols)
print(f"統(tǒng)計異常: {len(outliers)} 份")

第七步:匯總所有無效樣本

# 合并所有檢測結果
all_invalid = straight_lining | near_straight | speeders | patterns | outliers

print(f"\n{'='*50}")
print(f"原始數(shù)據(jù): {len(df)} 份")
print(f"直線作答: {len(straight_lining)} 份")
print(f"接近直線: {len(near_straight)} 份")
print(f"秒填樣本: {len(speeders)} 份")
print(f"規(guī)律作答: {len(patterns)} 份")
print(f"統(tǒng)計異常: {len(outliers)} 份")
print(f"總無效: {len(all_invalid)} 份")
print(f"有效率: {(1 - len(all_invalid)/len(df))*100:.1f}%")
print(f"{'='*50}")

# 標記無效樣本
df['is_invalid'] = df.index.isin(all_invalid)
df['invalid_reason'] = ''
df.loc[df.index.isin(straight_lining), 'invalid_reason'] += '直線作答;'
df.loc[df.index.isin(near_straight), 'invalid_reason'] += '接近直線;'
df.loc[df.index.isin(speeders), 'invalid_reason'] += '秒填;'
df.loc[df.index.isin(patterns), 'invalid_reason'] += '規(guī)律作答;'
df.loc[df.index.isin(outliers), 'invalid_reason'] += '統(tǒng)計異常;'

# 導出清洗結果
clean_df = df[~df['is_invalid']].copy()
clean_df.to_excel('問卷數(shù)據(jù)_已清洗.xlsx', index=False)

# 導出無效樣本明細(方便人工復核)
invalid_df = df[df['is_invalid']].copy()
invalid_df.to_excel('無效樣本明細.xlsx', index=False)

print(f"\n清洗后有效數(shù)據(jù): {len(clean_df)} 份")

第八步:可視化清洗結果

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 無效類型分布
reasons = {
    '直線作答': len(straight_lining),
    '接近直線': len(near_straight - straight_lining),
    '秒填': len(speeders),
    '規(guī)律作答': len(patterns),
    '統(tǒng)計異常': len(outliers),
}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# 左圖:無效類型柱狀圖
ax1.bar(reasons.keys(), reasons.values(), color='#ff6b6b')
ax1.set_title('無效樣本類型分布')
ax1.set_ylabel('份數(shù)')
for i, v in enumerate(reasons.values()):
    ax1.text(i, v + 0.5, str(v), ha='center')

# 右圖:有效率餅圖
valid = len(clean_df)
invalid = len(all_invalid) - valid + len(all_invalid)  # 避免雙重計算
ax2.pie([len(clean_df), len(all_invalid)],
        labels=['有效樣本', '無效樣本'],
        autopct='%1.1f%%',
        colors=['#51cf66', '#ff6b6b'])
ax2.set_title(f'樣本有效率 (總計 {len(df)} 份)')

plt.tight_layout()
plt.savefig('數(shù)據(jù)清洗報告.png', dpi=150)
plt.show()

完整代碼(一鍵運行)

把上面的函數(shù)整合成一個類,方便復用:

import pandas as pd
import numpy as np
from collections import Counter

class SurveyDataCleaner:
    """問卷數(shù)據(jù)清洗工具"""

    def __init__(self, filepath: str, question_cols: list = None):
        if filepath.endswith('.xlsx'):
            self.df = pd.read_excel(filepath)
        else:
            self.df = pd.read_csv(filepath)
        self.question_cols = question_cols or self._auto_detect_questions()
        self.invalid_sets = {}

    def _auto_detect_questions(self):
        cols = [c for c in self.df.columns
                if any(k in str(c) for k in ['Q', '第', '題'])]
        return cols

    def run_all(self, min_seconds=15, z_threshold=3.0, straight_threshold=0.8):
        self.invalid_sets['直線作答'] = self._detect_straight()
        self.invalid_sets['接近直線'] = self._detect_near_straight(straight_threshold)
        self.invalid_sets['秒填'] = self._detect_speeders(min_seconds)
        self.invalid_sets['規(guī)律作答'] = self._detect_pattern()
        self.invalid_sets['統(tǒng)計異常'] = self._detect_outliers(z_threshold)
        return self

    def _detect_straight(self):
        invalid = set()
        for idx, row in self.df.iterrows():
            ans = row[self.question_cols].dropna().tolist()
            if len(ans) >= 3 and len(set(ans)) == 1:
                invalid.add(idx)
        return invalid

    def _detect_near_straight(self, threshold):
        invalid = set()
        for idx, row in self.df.iterrows():
            ans = row[self.question_cols].dropna().tolist()
            if len(ans) >= 3:
                counts = Counter(ans)
                if counts.most_common(1)[0][1] / len(ans) >= threshold:
                    invalid.add(idx)
        return invalid

    def _detect_speeders(self, min_seconds):
        duration_col = [c for c in self.df.columns
                       if '時長' in str(c) or '用時' in str(c)]
        if not duration_col:
            return set()
        durations = pd.to_numeric(self.df[duration_col[0]], errors='coerce')
        return set(self.df[durations < min_seconds].index)

    def _detect_pattern(self):
        invalid = set()
        for idx, row in self.df.iterrows():
            ans = row[self.question_cols].dropna().tolist()
            if len(ans) < 5:
                continue
            try:
                numeric = pd.array(ans, dtype='float')
                diffs = np.diff(numeric)
                if len(diffs) > 0 and np.all(diffs == diffs[0]) and diffs[0] != 0:
                    invalid.add(idx)
            except:
                pass
        return invalid

    def _detect_outliers(self, threshold):
        numeric_df = self.df[self.question_cols].apply(
            pd.to_numeric, errors='coerce')
        row_means = numeric_df.mean(axis=1)
        z_scores = (row_means - row_means.mean()) / row_means.std()
        return set(self.df[abs(z_scores) > threshold].index)

    @property
    def all_invalid(self):
        result = set()
        for s in self.invalid_sets.values():
            result |= s
        return result

    @property
    def clean_data(self):
        return self.df[~self.df.index.isin(self.all_invalid)].copy()

    def report(self):
        total = len(self.df)
        invalid_count = len(self.all_invalid)
        print(f"\n{'='*50}")
        print(f"問卷數(shù)據(jù)清洗報告")
        print(f"{'='*50}")
        print(f"原始樣本量: {total} 份")
        for reason, indices in self.invalid_sets.items():
            print(f"  {reason}: {len(indices)} 份")
        print(f"{'─'*50}")
        print(f"無效樣本合計: {invalid_count} 份")
        print(f"有效樣本: {total - invalid_count} 份")
        print(f"有效率: {(1 - invalid_count/total)*100:.1f}%")
        print(f"{'='*50}")

    def export(self, output_path='清洗結果'):
        clean = self.clean_data
        clean.to_excel(f'{output_path}_有效數(shù)據(jù).xlsx', index=False)

        invalid_df = self.df[self.df.index.isin(self.all_invalid)].copy()
        invalid_df['無效原因'] = ''
        for reason, indices in self.invalid_sets.items():
            invalid_df.loc[invalid_df.index.isin(indices), '無效原因'] += f'{reason};'
        invalid_df.to_excel(f'{output_path}_無效樣本.xlsx', index=False)


# 使用方法
if __name__ == '__main__':
    cleaner = SurveyDataCleaner('問卷數(shù)據(jù).xlsx')
    cleaner.run_all(min_seconds=15, z_threshold=3.0)
    cleaner.report()
    cleaner.export()

關于樣本質量的一個延伸

清洗完數(shù)據(jù)之后,很多人會發(fā)現(xiàn)一個問題:有效樣本量不夠了。

比如原本收了 300 份,洗完只剩 200 份,但你的論文需要 250 份以上的有效樣本。這時候要么繼續(xù)補數(shù)據(jù),要么回頭看看無效樣本率是不是太高了。

如果無效樣本率超過 20%,通常說明數(shù)據(jù)來源本身有問題——要么是分發(fā)渠道不合適,要么是激勵方式導致亂填。

這也是為什么在做學術研究時,樣本來源的選擇很重要。相比在互填群里收回大量低質量數(shù)據(jù),問卷鴨 這種真人分發(fā)渠道的無效樣本率通常會更低,因為它走的是真實用戶逐份填寫,而不是批量自動化。價格大概是 0.2 元一份,如果你算一下重新收集數(shù)據(jù)的時間成本,其實并不貴。

不過不管數(shù)據(jù)來源是什么,拿到手之后該做的清洗一步都不能少。上面的代碼覆蓋了最常見的清洗場景,如果需要做信效度分析(Cronbach’s Alpha、KMO 檢驗等),可以結合 factor_analyzer 庫繼續(xù)做。

以上就是使用Python清洗問卷數(shù)據(jù)的實戰(zhàn)方法的詳細內容,更多關于Python清洗問卷數(shù)據(jù)的資料請關注腳本之家其它相關文章!

相關文章

  • Python實現(xiàn)ping指定IP的示例

    Python實現(xiàn)ping指定IP的示例

    今天小編就為大家分享一篇Python實現(xiàn)ping指定IP的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • Python繪制正余弦函數(shù)圖像的方法

    Python繪制正余弦函數(shù)圖像的方法

    這篇文章主要介紹了Python繪制正余弦函數(shù)圖像的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Pyramid Mako模板引入helper對象的步驟方法

    Pyramid Mako模板引入helper對象的步驟方法

    ylons中的mako模板,默認會引入一個helper對象,我們可以在里面擴展方法,應對在模板輸出時候會常用的操作,那么在Pyramid中如何默認引入同樣的輔助類到模板中
    2013-11-11
  • tensorflow+k-means聚類簡單實現(xiàn)貓狗圖像分類的方法

    tensorflow+k-means聚類簡單實現(xiàn)貓狗圖像分類的方法

    這篇文章主要介紹了tensorflow+k-means聚類簡單實現(xiàn)貓狗圖像分類,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • Python實現(xiàn)一行代碼自動繪制藝術畫

    Python實現(xiàn)一行代碼自動繪制藝術畫

    DiscoArt?是一個很牛的開源模塊,它能根據(jù)你給定的關鍵詞自動繪畫。本文就將利用這一模塊實現(xiàn)一行代碼自動繪制藝術畫,需要的可以參考一下
    2022-12-12
  • 淺談Python中chr、unichr、ord字符函數(shù)之間的對比

    淺談Python中chr、unichr、ord字符函數(shù)之間的對比

    chr、unichr、ord在Python中都可以被用作字符類型轉換,這里我們就來淺談Python中chr、unichr、ord字符函數(shù)之間的對比,需要的朋友可以參考下
    2016-06-06
  • 在Pandas中使用透視表后去掉多級索引的方法

    在Pandas中使用透視表后去掉多級索引的方法

    Pandas是一個功能強大且通用的Python庫,用于數(shù)據(jù)操作和分析,它最有用的特性之一是數(shù)據(jù)透視表,它允許您重塑和匯總數(shù)據(jù),但是,使用數(shù)據(jù)透視表通常會導致多級(分層)索引,在本文中,我們將探討如何在Pandas中使用透視表后去掉多級索引,需要的朋友可以參考下
    2024-12-12
  • python數(shù)據(jù)分析之時間序列分析詳情

    python數(shù)據(jù)分析之時間序列分析詳情

    這篇文章主要介紹了python數(shù)據(jù)分析之時間序列分析詳情,時間序列分析是基于隨機過程理論和數(shù)理統(tǒng)計學方法,具體詳細內容介紹,需要的小伙伴可以參考一下
    2022-08-08
  • python中sample函數(shù)的介紹與使用

    python中sample函數(shù)的介紹與使用

    sample()函數(shù)常用來隨機獲取dataFrame中數(shù)據(jù),可以用于快速查看,下面這篇文章主要給大家介紹了關于python中sample函數(shù)的介紹與使用的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-09-09
  • Python GUI之如何使用tkinter控件

    Python GUI之如何使用tkinter控件

    今天帶大家學習Python GUI的相關知識,文中對如何使用tkinter控件作了非常詳細的介紹及代碼示例,對正在學習python的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05

最新評論

东辽县| 鄂托克旗| 富平县| 穆棱市| 阳东县| 福州市| 晋中市| 朝阳县| 改则县| 甘洛县| 都昌县| 麟游县| 巴南区| 宁安市| 龙南县| 巴彦县| 南陵县| 墨竹工卡县| 乌兰浩特市| 巴彦县| 肃南| 赤壁市| 察隅县| 仁布县| 渭南市| 扶风县| 崇阳县| 大田县| 襄垣县| 开原市| 桃园县| 普洱| 福建省| 镇沅| 阳山县| 木里| 永仁县| 嘉黎县| 三门峡市| 东山县| 五峰|