Using df.apply

pd.Series.str.replace is a series method not for dataframes. You can use apply on each column (series) instead.

dataFrame[headers] = dataFrame[headers].apply(lambda x: x.str.replace(',', ''))

Another option is to use apply on each row (series) with axis=1.

Using df.applymap

Or, you can use applymap and treat each cell as a string and use replace directly on them.

dataFrame[headers] = dataFrame[headers].applymap(lambda x: x.replace(',', ''))

Using df.replace

You can also use df.replace which is a method available to replace values in df directly across all columns selected. But, for this purpose you will have to set regex=True.

dataFrame[headers] = dataFrame[headers].replace(',', '', regex=True)
Answer from Akshay Sehgal on Stack Overflow
🌐
Quora
quora.com › What-is-a-possible-solution-for-attributeerror-index-object-has-no-attribute-replace-Python-pandas-replace-development
What is a possible solution for attributeerror: 'index' object has no attribute 'replace' (Python, pandas, replace, development)? - Quora
Answer: This is a very standard syntax error. When you make a class, the variables associated to that class are attributes and the functions associated with it are methods. The error is you are trying to call the “replace” variable when ...
Discussions

python - Trying to change pandas column dtype from str to float - Data Science Stack Exchange
I am trying to convert a pandas column from a str to a float. Before I convert the strings to floats using astype(float), I need to remove characters from the string which cannot be converted into ... More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
python - AttributeError: 'DataFrame' object has no attribute - Stack Overflow
I keep getting different attribute errors when trying to run this file in ipython...beginner with pandas so maybe I'm missing something Code: from pandas import Series, DataFrame import pandas a... More on stackoverflow.com
🌐 stackoverflow.com
python - Trying to use replace method with pandas - Stack Overflow
from pandas import * In [2]: df = DataFrame({1: [2,3,4], 2: [3,4,5]}) In [4]: df[2] Out[4]: 0 3 1 4 2 5 Name: 2 In [5]: df[2].replace(4, 17) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) c:\Python27\ in () ----> 1 df[2].replace(4, 17) AttributeError: 'Series' object has no ... More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
python - How to resolve AttributeError: 'DataFrame' object has no attribute - Stack Overflow
I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Edureka Community
edureka.co › home › community › categories › python › python pandas error attributeerror dataframe ...
Python Pandas error AttributeError DataFrame object has no attribute rows | Edureka Community
March 28, 2019 - I am trying to print each entry of the dataframe separately. The dataframe is created by reading ... : 'DataFrame' object has no attribute 'rows'
Find elsewhere
Top answer
1 of 5
2

"sklearn.datasets" is a scikit package, where it contains a method load_iris().

load_iris(), by default return an object which holds data, target and other members in it. In order to get actual values you have to read the data and target content itself.

Whereas 'iris.csv', holds feature and target together.

FYI: If you set return_X_y as True in load_iris(), then you will directly get features and target.

from sklearn import datasets
data,target = datasets.load_iris(return_X_y=True)
2 of 5
1

The Iris Dataset from Sklearn is in Sklearn's Bunch format:

print(type(iris))
print(iris.keys())

output:

<class 'sklearn.utils.Bunch'>
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])

So, that's why you can access it as:

x=iris.data
y=iris.target

But when you read the CSV file as DataFrame as mentioned by you:

iris = pd.read_csv('iris.csv',header=None).iloc[:,2:4]
iris.head()

output is:

    2   3
0   petal_length    petal_width
1   1.4 0.2
2   1.4 0.2
3   1.3 0.2
4   1.5 0.2

Here the column names are '1' and '2'.

First of all you should read the CSV file as:

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

you should not include header=None as your csv file includes the column names i.e. the headers.

So, now what you can do is something like this:

X = df.iloc[:, [2, 3]] # Will give you columns 2 and 3 i.e 'petal_length' and 'petal_width'
y = df.iloc[:, 4] # Label column i.e 'species'

or if you want to use the column names then:

X = df[['petal_length', 'petal_width']]
y = df.iloc['species']

Also, if you want to convert labels from string to numerical format use sklearn LabelEncoder

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y = le.fit_transform(y)
Top answer
1 of 3
3

What you are trying to do is not practical - in any language.

First, as others have said, there is no replace() method on a file object.

More importantly you don't seem to understand how text files work. You say: "I saw some answers when they create a new file everytime". Did you consider why they do that?

"I just need to add +1 to an specific line"

Let's take a couple of lines in a text file that you think looks like this:

onetwomumble9
threefourmumble3

But a text file is nothing special, it just goes from the first byte to the last with newlines showing where lines end. It really looks like this:

onetwomumble9\nthreefourmumble3\n

Where \n represents the single newline character.

Let's say that you did replace 9 with 10 and 3 with 4. The problem is that 10 is wider than 9 and the extra character will overwrite the newline (or any other character) which follows. So you end-up with this:

onetwomumble10threefourmumble4\n

You lost the newline!

That's why you have to copy the file to update it! The alternative is to use a database (like SQLite) which handles these issues.

There are a few work-arounds. The simplest is to decide on an absolute maximum number of characters, and pad with zeros, for example 0009 gets updated to 0010.

Let's say the file looks like this:

onetwomumble0009
threefourmumble0005
sixsevenmumble0067
eightnonemumber0042

For reading and writing to the same file, you have to maintain the file position yourself. When you read a line it puts the current position to the next line, so to rewrite a line you have to move it back. Example code:

import re
import sys

# Could be done as a one-line lambda, but would be difficult to read
def addit(m):
    num = m.groups()[0]
    new_num = "%04d" % (int(num) + 1)
    return new_num

line_number = 1

with open('gash.txt', 'r+') as uf:
    while True:
        start_pos = uf.tell()  # Get start of line position
        line = uf.readline()
        if not line : break
        end_pos = uf.tell()  # Get end of line position - needed if updating more than one line

        # Let's say we update line 2, and we decided on 4 chars
        if line_number == 2: 
            # Do the add
            newline = re.sub(r'(\d{4})$', addit, line)


            # Sanity check
            if len(newline) != len(line):
                print("line length changed!", line, file=sys.stderr)
                sys.exit(1)

            # Seek to start of line just read and write
            uf.seek(start_pos)
            uf.write(newline)
            # Seek to start of next line
            uf.seek(end_pos)

            # If we only wanted to update one line, we can:
            break

        line_number += 1
2 of 3
1

Obviously a _io.TextIOWrapper i.e. a file object will not have a replace method which is a string function. I think you're trying to make replacements in the entire file. Here is a quick fix.

file_data = ''.join(lines)
# Now apply your replacements here
file_data = file_data.replace(str(x),str(y))  
🌐
GitHub
github.com › dask › dask › issues › 8624
AttributeError: 'DataFrame' object has no attribute 'name'; Various stack overflow / github suggested fixes not working · Issue #8624 · dask/dask
January 26, 2022 - { File "[redacted]/pandas/core/generic.py", line 5487, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'name'. Did you mean: 'rename'? }
Author   david-thrower
🌐
Reddit
reddit.com › r/learnpython › attributeerror: 'dataframe' object has no attribute 'data'
r/learnpython on Reddit: AttributeError: 'DataFrame' object has no attribute 'data'
September 29, 2021 -
wine = pd.read_csv("combined.csv", header=0).iloc[:-1]
df = pd.DataFrame(wine)
df
dataset = pd.DataFrame(df.data, columns =df.feature_names)
dataset['target']=df.target
dataset

ERROR:

<ipython-input-27-64122078da92> in <module>
----> 1 dataset = pd.DataFrame(df.data, columns =df.feature_names)
      2 dataset['target']=df.target
      3 dataset

D:\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5464                 return self[name]
-> 5465             return object.__getattribute__(self, name)
   5466 
   5467     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'data'

I'm trying to set up a target to proceed with my Multi Linear Regression Project, but I can't even do that. I've already downloaded the CSV file and have it uploaded on a Jupyter Notebook. What I'm I doing wrong?

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-fix-module-pandas-has-no-attribute-dataframe
How to Fix: module ‘pandas’ has no attribute ‘dataframe’ - GeeksforGeeks
December 19, 2021 - To create dataframe we need to use DataFrame(). If we use dataframe it will throw an error because there is no dataframe attribute in pandas. The method is DataFrame(). We need to pass any dictionary as an argument. Since the dictionary has ...
🌐
Reddit
reddit.com › r/learnpython › why am i suddenly getting "attributeerror: 'index' object has no attribute 'apply'"?
r/learnpython on Reddit: Why am I suddenly getting "AttributeError: 'Index' object has no attribute 'apply'"?
February 28, 2023 -

I don't understand... This exact code works for this same dataset look for different "X" variables, but now it is giving me this error...?

My code:

Import os Import pandas as pd

Os.chdir('file locations')

df = pd.read_csv('reading the file.csv') df = df.columns.str.replace(' ', '_')

def alphabet (row): If any(x in ['A', 'B', 'C'] for x in [row['alphanumeric_1'], row['alphanumeric_2]]): return 1 else: return 0

df['alphabet_yn] = df.apply(lambda row: alphabet (row), axis =1)

I don't understand why I am getting the AttributeError on the final line.

I am on my phone, so I apologize for how hard this might be to understand.

🌐
GitHub
github.com › pandas-dev › pandas › issues › 47480
BUG: DataFrame.replace fails to replace value when column contains pd.NA · Issue #47480 · pandas-dev/pandas
June 23, 2022 - I have checked that this issue has not already been reported. I have confirmed this bug exists on the latest version of pandas. I have confirmed this bug exists on the main branch of pandas. import pandas as pd df = pd.DataFrame({'A': [0, 1, 2]}) print(df) # A # 0 0 # 1 1 # 2 2 df['A'].replace(to_replace=2, value=99, inplace=True) print(df) # A # 0 0 # 1 1 # 2 99 df.at[0, 'A'] = pd.NA df['A'].replace(to_replace=1, value=100, inplace=True) print(df) # A # 0 <NA> # 1 1 <-- should be 100 # 2 99
Author   pschwientek
🌐
Python Forum
python-forum.io › thread-23576.html
Attribute Error for Rename / Replace
December 14, 2020 - Hello Everyone - I'm very new to python and I have a use case where I need to rename .zip files and then extract. I think I have the extraction part down (it is commented out for the time being) but I am having trouble with the rename portion. My di...
🌐
Reddit
reddit.com › r/learnpython › "'dataframe' object has no attribute" issue
r/learnpython on Reddit: "'DataFrame' object has no attribute" Issue
October 30, 2020 -

I am in university and am taking a special topics class regarding AI. I have zero knowledge about Python, how it works, or what anything means.

A project for the class involves manipulating Bayesian networks to predict how many and which individuals die upon the sinking of a ship. This is the code I am supposed to manipulate:

##EDIT VARIABLES TO THE VARIABLES OF INTEREST
train_var = train.loc[:,['Survived','Sex']]  
test_var = test.loc[:,['Sex']]  
BayesNet = BayesianModel([('Sex','Survived')])

I am supposed to add another variable, 'Pclass,' to the mix, paying attention to the order for causation. I have added that variable to every line of this code in every way imaginable and consistently get an error from this line:

predictions = pandas.DataFrame({'PassengerId': test.PassengerId,'Survived': hypothesis.Survived.tolist()})
predictions

For example, the error I get for this version of the code:

train_var = train.loc[:,['Survived','Pclass','Sex']]  
test_var = test.loc[:,['Pclass']]  
BayesNet = BayesianModel([('Sex','Pclass','Survived')])

is this:

AttributeError                            Traceback (most recent call last)
<ipython-input-98-16d9eb9451f7> in <module>
----> 1 predictions = pandas.DataFrame({'PassengerId': test.PassengerId,'Survived': hypothesis.Survived.tolist()})
      2 predictions

/opt/conda/lib/python3.7/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5137             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5138                 return self[name]
-> 5139             return object.__getattribute__(self, name)
   5140 
   5141     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'Survived'

Honestly, I have no idea wtf any of this means. I have tried googling this issue and have come up with nothing.

Any help would be greatly appreciated. I know it's a lot.

🌐
GitHub
github.com › pycaret › pycaret › issues › 195
AttributeError: 'DataFrame' object has no attribute 'dtype' · Issue #195 · pycaret/pycaret
June 3, 2020 - This is necessary when loading ... return object.__getattribute__(self, name) 5275 5276 def __setattr__(self, name: str, value) -> None: AttributeError: 'DataFrame' object has no attribute 'dtype'...
Author   sorenwacker