Wie behebe ich Namensfehler beim Anwenden von Funktionen auf mehrere Spalten in Pandas?

Linda Hamilton
Freigeben: 2024-10-18 07:30:30
Original
117 Leute haben es durchsucht

How to Troubleshoot NameErrors When Applying Functions to Multiple Columns in Pandas?

Troubleshooting Pandas 'apply' Function with Multiple Column Referencing

In an attempt to apply a custom function to multiple columns in a Pandas DataFrame, the 'apply' function is encountering a NameError.

The error message, "global name 'a' is not defined," indicates that the 'a' variable is not accessible within the function. Upon closer examination, it emerges that the column name should be enclosed in quotes, as in 'row['a']'.

The corrected code should look like this:

<code class="python">df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)</code>
Nach dem Login kopieren

However, even after resolving this syntax error, the code still fails when using a more complex function. This suggests a different issue.

A critical step in the provided function is to iterate through the DataFrame's index and compare the parameter 'a' with each value in column 'a'. To access these elements, the syntax should be adjusted as follows:

<code class="python">def my_test(a):
    cum_diff = 0
    for ix in df.index:
        cum_diff += (a - df['a'][ix])
    return cum_diff</code>
Nach dem Login kopieren

By incorporating these corrections, the code should now function as expected.

Das obige ist der detaillierte Inhalt vonWie behebe ich Namensfehler beim Anwenden von Funktionen auf mehrere Spalten in Pandas?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!