簡體   English   中英

根據相同的標題前綴從多個 DataFrame 中選擇列

[英]Select column from multiple DataFrames based on same header prefix

我有一個函數,它遍歷Age列的csv行,如果年齡為負,它將把KeyAge值打印到文本文件中。

def neg_check():
    results = []

    file_path = input('Enter file path: ')
    file_data = pd.read_csv(file_path, encoding = 'utf-8')
    
    for index, row in file_data.iterrows():
        if row['Age'] < 0:
            results.append((row['Key'], row['Age']))
    with open('results.txt', 'w') as outfile:
        outfile.write("\n".join(map(str, results)))   
        outfile.close()

為了使此代碼可重復,我該如何修改它,以便它在列以“ Age ”開頭時迭代行? 我的文件有許多列以“ Age ”開頭但以不同的方式結束。 . 我嘗試了以下...

if row.startswith['Age'] < 0:

if row[row.startswith('Age')] < 0:

但它拋出AttributeError: 'Series' object has no attribute 'startswith'錯誤。

我的 csv 文件:

樣本 1

Key   Sex     Age
    1        Male          46
    2        Female        34

樣本 2

Key   Sex     AgeLast
    1        Male          46
    2        Female        34

樣本 3

Key   Sex     AgeFirst
    1        Male          46
    2        Female        34

我會一步完成,但有幾種選擇。 一種是filter

v = df[df.filter(like='AgeAt').iloc[:, 0] < 0]

或者,

c = df.columns[df.columns.str.startswith('AgeAt')][0]
v = df[df[c] < 0]

最后,要寫入 CSV,請使用

if not v.empty:
    v.to_csv('invalid.csv')

使用熊貓不需要循環數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM