【问题标题】:Type Conversion in python AttributeError: 'str' object has no attribute 'astype'python AttributeError中的类型转换:'str'对象没有属性'astype'
【发布时间】:2018-07-26 21:29:37
【问题描述】:

我对 python pandas 中的类型转换感到困惑

df = pd.DataFrame({'a':['1.23', '0.123']})
type(df['a'])
df['a'].astype(float)

这里df是一个pandas系列,它的内容是2个字符串,然后我可以在这个pandas系列上应用astype(float),它正确地将所有字符串转换为float。不过

df['a'][1].astype(float)

给我 AttributeError: 'str' object has no attribute 'astype'。我的问题是:怎么可能?我可以将整个系列从字符串转换为浮点数,但我无法将这个系列的条目从字符串转换为浮点数?

另外,我加载了我的原始数据集

df['id'].astype(int)

它生成 ValueError: invalid literal for int() with base 10: '' 这似乎表明我的df['id'] 中有一个空白。所以我通过输入来检查它是否是真的

'' in df['id']

它说的是假的。所以我很困惑。

【问题讨论】:

  • 你必须像这样使用df['a'].iloc[1].astype(float),它不会抛出错误

标签: python pandas type-conversion


【解决方案1】:

df['a'] 返回一个 Series 对象,该对象具有 astype 作为矢量化方式,将系列中的所有元素转换为另一个元素。

df['a'][1] 返回数据框的一个单元格的内容,在本例中为字符串'0.123'。这现在返回一个没有此功能的str 对象。要转换它,请使用常规 python 指令:

type(df['a'][1])
Out[25]: str

float(df['a'][1])
Out[26]: 0.123

type(float(df['a'][1]))
Out[27]: float

根据您的第二个问题,最后调用 __contains__ 的运算符 in 针对以 '' 作为参数的系列,这里是运算符的文档字符串:

help(pd.Series.__contains__)
Help on function __contains__ in module pandas.core.generic:

__contains__(self, key)
    True if the key is in the info axis

这意味着in 操作符在索引中搜索你的空字符串,而不是它的内容。

搜索空字符串的方法是使用等号:

df
Out[54]: 
    a
0  42
1    

'' in df
Out[55]: False

df==''
Out[56]: 
       a
0  False
1   True

df[df['a']=='']
Out[57]: 
  a
1  

【讨论】:

  • 谢谢!我有一个简短的后续问题。所以在你的例子df中,如果我想检查42号是否在df中,我不应该使用42 in df42 in df['a']42 in df[['a']]对吗? in 正在检查熊猫系列的索引?但是df[['a']] 呢?这是一个熊猫数据框。那么in在对dataframe进行操作的时候还在检查索引吗?
  • 数据帧的相同机制。 df==42 也是如此
【解决方案2】:

df['a'][1] 将返回数组中的实际值,位于1 的位置,实际上是一个字符串。您可以使用float(df['a'][1]) 进行转换。

>>> df = pd.DataFrame({'a':['1.23', '0.123']})
>>> type(df['a'])
<class 'pandas.core.series.Series'>
>>> df['a'].astype(float)
0    1.230
1    0.123
Name: a, dtype: float64
>>> type(df['a'][1])
<type 'str'>

对于第二个问题,您的原始数据可能有一个空值。正确的测试是:

>>> df = pd.DataFrame({'a':['1', '']})
>>> '' in df['a'].values
True

第二个问题来源:https://stackoverflow.com/a/21320011/5335508

【讨论】:

    【解决方案3】:
    data1 = {'age': [1,1,2, np.nan],
            'gender': ['m', 'f', 'm', np.nan],
            'salary': [2,1,2, np.nan]}
    
    x = pd.DataFrame(data1)
    for i in list(x.columns):
        print(type((x[i].iloc[1])))
        if isinstance(x[i].iloc[1], str):
            print("It is String")
        else:
            print('Not a String')
    

    【讨论】:

    • 这里不欢迎发布没有任何解释的代码。请编辑您的帖子。
    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 2018-12-01
    • 2015-09-30
    • 2021-10-22
    • 2020-09-22
    • 2020-06-25
    • 2016-12-27
    • 2015-03-08
    相关资源
    最近更新 更多