首页 > 解决方案 > 如何将字符串的数据类型更改为条件值的相同数据类型?

问题描述

我正在尝试实施过滤代码:

例如:

import pandas as pd   
import operator              #this lets you do logical operations

df = pd.read_csv('file.csv')

Filter_column = input('> ')  # I will do a filter in this column
comparision = input('> ')    # Here goes the logical comparission (==, >, <, etc)
filter_value = input('> ')   # Here goes the value to do the filter 

if comparision == '=':       #Say comparision = '=' in this example

    filter_value.astype(type(df['Filter_column)].dropna()[0])) #!!!
    filter = operator.eq(df['Filter_column'],filter_value))
    dp = df[filter]

那么,dp就是给定过滤条件的过滤数据集

在我放注释的那一行#!!!是转换输入字符串的数据类型的理想方法filter_value。Pandas 可以使用方法更改列值的数据类型.astype()。但这不是字符串的有效方法。有没有办法将输入字符串的数据类型转换为任意给定对象的相同数据类型?

标签: pythonstringpandastype-conversion

解决方案


推荐阅读