简体   繁体   中英

How do I convert a string into code in Python?

Converting a string to code

Noteworthy points:

  • I'm new to coding and am testing various things to learn;
  • ie yes, I'm sure there are better ways do achieve what I am trying to do;
  • I would like to know any alternative / more efficient methods, however;
  • I would also still like to know how to convert string to code to achieve my goal with this technique

So far I have looked around the forum and on google, and seen a few topics on this, none of which I can made work here, or which precisely answer the question from my perspective, including using eval and exec .

The Scenario

  • I have a dataframe: london with 23 columns
  • I want to create a dataframe showing all rows with 'NaN' values
  • I have tried to use .isnull() , but it appears to only work on a single column at a time
  • I am trying to achieve my desired result by using | to return any rows in any columns where .isnull() returns True

An example of this working with just two columns is:

london[(london['Events'].isnull() | london['Max Gust SpeedKm/h'].isnull())]

However, I need to achieve this result with all 23 columns, so I have attempted to complete this with some code.

Attempted Solution

  • Creating a string containing all of the column headers
  • ie london[(london[' Column Header '].isnull() followed by | and then the next column
  • Then using this string within the container shown in the working example above
  • ie london[( string )]

I have managed to create the string I need using the following:

string = []
for i in (london.columns.values):
    string.append("london['" + i + "'].isnull()")
    string.append(" | ")
del string[-1]
final_string = "".join(string)

And finally when I try to implement the final step, I cannot work out how to convert this string into usable code.

For example:

now = eval(final_string)
london[now]

Resulting in:
NotImplementedError: 'Call' nodes are not implemented

Thank you in advance.

这是使用NaN值选择数据框中rows的最简单方法:

df[pd.isnull(df).any(axis=1)]
string = []
for i in (london.columns.values):
    string.append(london[i].isnull())
london[0<sum(string)]

Since you will have only 1 and 0 and you are looking for at least one 1 then you can just add 1,0's to your list then sum them. if the sum is more than one your if will turn 1 otherwise your if will turn 0 so you can do london index after that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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