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"
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.
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.
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.
Use DataFrame.empty attribute empty attribute to check if the given dataframe is empty or not.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With