简体   繁体   English

确定 object 是字符串还是 dataframe

[英]Determining whether an object is a string or a dataframe

I have some variables and single column dataframes.我有一些变量和单列数据框。

I'm trying to arrange them (concat) into a single dataframe.我正在尝试将它们(连接)排列成一个 dataframe。

The problem is that some are single strings, some single column dataframes and I'm trying to loop through them, so I have to use different methods for the different types.问题是有些是单字符串,有些是单列数据框,我正在尝试遍历它们,所以我必须对不同的类型使用不同的方法。

I've tried the following to determine if a single string or a dataframe is being passed.我尝试了以下方法来确定是否正在传递单个字符串或 dataframe。

data = {'Column Name':  ['First value', 'Second value']}
a_dataframe = pd.DataFrame (data, columns = ['Column Name'])

a_single_string = 'text'
another_string = 'more text'

feature_cols = ['a_single_string', 'a_dataframe', 'another_string']

for column in feature_cols:
    if column in locals():
        if isinstance(column, str):
            print("str: " + column)

        elif isinstance(column, pd.DataFrame):
            print("df: " + column)

But it sees the strings and dataframe as strings.但它将字符串和 dataframe 视为字符串。
Any solutions?有什么解决办法吗?

Your code defines feature_cols as a list of strings.您的代码将feature_cols定义为字符串列表。 So your isinstance() test is returning the type of the string 'a_dataframe' , which is not the same thing as the variable a_dataframe .因此,您的isinstance()测试返回的是字符串'a_dataframe'的类型,这与变量a_dataframe

This will fix your test:这将修复您的测试:

feature_cols = [a_single_string, a_dataframe, another_string]

You also won't be able to do if column in locals(): because that expects the name as a string (as in your original code) not the variable.您也无法if column in locals():因为这需要将名称作为字符串(如在您的原始代码中)而不是变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM