根据相同的标题前缀从多个DataFrame中选择列

时间:2018-12-05 20:21:08

标签: python python-3.x pandas dataframe

我有一个函数可以对csv列的Age行进行迭代,如果年龄为负数,它将打印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

1 个答案:

答案 0 :(得分:2)

我将一步一步完成此操作,但是有一些选择。一个是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')

使用熊猫不必遍历数据。

相关问题