When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Answer from foglerit on Stack OverflowI have a dataframe that I've moved down to two columns 'last date read' and 'read count'. I formatted it to %Y-%m and then grouped it using the dates and summed the total amount of books read.
I wanted to plot it using month_calplot from plotly_calplot but I get the following error and I'm not sure where to go from here:
Error:
line 247, in month_calplot
gData = data.set_index(x)[y].groupby(Grouper(freq="M")).sum()
File "C:\Python\Python310\lib\site-packages\pandas\core\generic.py", line 5575, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'Series' object has no attribute 'set_index'Code:
df2 = df2[['last date read', 'read count']]
df2['last date read'] = pd.to_datetime(df2['last date read'])
df2['last date read'] = df2['last date read'].dt.strftime('%Y-%m')
df2 = df2.groupby(['last date read'])['read count'].sum()
print(df2)
fig3 = month_calplot(
df2,
x='last date read',
y='read count',
colorscale="Purpor",
showscale=True,
total_height=250,
dark_theme=True)AttributeError: 'Series' object has no attribute [X] when preparing DataBlock - Part 1 (2020) - fast.ai Course Forums
python - Pandas - 'Series' object has no attribute - Stack Overflow
AttributeError: 'Series' object has no attribute 'labelNames'
Python Pandas AttributeError: 'Series' object has no attribute 'columns' - Stack Overflow
When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
In general, this error occurs if you try to access an attribute that doesn't exist on an object. For pandas Serieses (or DataFrames), it occurs because you tried to index it using the attribute access (.).
In the case in the OP, they used x.colNames[0] to access the value on colNames[0] in row x but df doesn't have attribute colNames, so the error occurred.1
Another case this error may occur is if an index had a white space in it that you didn't know about. For example, the following case reproduces this error.
s = pd.Series([1, 2], index=[' a', 'b'])
s.a
In this case, make sure to remove the white space:
s.index = [x.strip() for x in s.index]
# or
s.index = [x.replace(' ', '') for x in s.index]
Finally, it's always safe to use [] to index a Series (or a DataFrame).
1: Serieses have the following attributes: axes, dtypes, empty, index, ndim, size, shape, T, values. DataFrames have all of these attributes + columns. When you use df.apply(..., axis=1), it iterates over the rows where each row is a Series whose indices are the column names of df.
Check the version of your pandas library:
import pandas
print(pandas.__version__)
If your version is less than 0.24.1:
pip install --upgrade pandas
If you need your code to work with all versions of pandas, here's a simple way to convert a Series into a NumPy array:
import pandas as pd
import numpy as np
s = pd.Series([1.1, 2.3])
a = np.array(s)
print(a) # [1.1 2.3]
On an advanced note, if your Series has missing values (as NaN values), these can be converted to a masked array:
s = pd.Series([1.1, np.nan])
a = np.ma.masked_invalid(s)
print(a) # [1.1 --]
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.