Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: pandas.DataFrame,how to avoid keyerror?

In C++, when I can't find a keyword in a table, it will return NULL or in database it will return a empty table, so the program continues to run. But in python, it throws an exception, and interrupts my program. Can I avoid that? for example, I have such a DataFrame named datevar :

(datetimeIndex)   value
2001-01-01           1
2001-01-02           1
2001-01-03           3
....

v = datevar.xs('2000-01-01', level='date') # of course "keyError"
v = datevar.loc['2000-01-01' , :]          # of course "keyError"
like image 343
acneyouth Avatar asked May 16 '18 06:05

acneyouth


People also ask

How do you stop pandas from SettingWithCopyWarning?

One approach that can be used to suppress SettingWithCopyWarning is to perform the chained operations into just a single loc operation. This will ensure that the assignment happens on the original DataFrame instead of a copy. Therefore, if we attempt doing so the warning should no longer be raised.

What is the best way to iterate through a DataFrame?

Vectorization is always the first and best choice. You can convert the data frame to NumPy array or into dictionary format to speed up the iteration workflow. Iterating through the key-value pair of dictionaries comes out to be the fastest way with around 280x times speed up for 20 million records.

How do I get rid of pandas indexing?

The most straightforward way to drop a Pandas dataframe index is to use the Pandas . reset_index() method. By default, the method will only reset the index, forcing values from 0 - len(df)-1 as the index.

How do you check if the DataFrame is empty?

Use DataFrame.empty attribute empty attribute to check if the given dataframe is empty or not.


1 Answers

I think you can check if the index is existed in the df's index or the columns before you get the value of that key.

df = pd.read_clipboard()
df
Out[6]: 
  (datetimeIndex)  value
0      2001-01-01      1
1      2001-01-02      1
2      2001-01-03      3
key = "2000-01-01"
if key in df.index:
    v = df.xs('2000-01-01', level='date')  # of course "keyError"
    v = df.loc['2000-01-01', :]  # of course "keyError"
else:
    v = None
v
like image 198
lihua Avatar answered Sep 30 '22 17:09

lihua