+

Python | Pandas DataFrame.truncate

DataFrame.truncate() Pandas DataFrame.truncate() is used to truncate a Series or DataFrame to and after some index value. This is a useful shorthand for logical indexing based on index values ​​above or below certain thresholds.

Syntax: DataFrame.truncate (before = None, after = None, axis = None, copy = True)

Parameter:
before: Truncate all rows before this index value.
after: Truncate all rows after this index value.
axis: Axis to truncate. Truncates the index (rows) by default.
copy: Return a copy of the truncated section.

Returns: The truncated Series or DataFrame.

Example # 1: Use DataFrame.truncate () to DataFrame.truncate () some entries before and after the passed labels of this data frame.

# import pandas as pd

import pandas as pd

  
# Create DataFrame

df = pd.DataFrame ({ ` Weight` : [ 45 , 88 , 56 , 15 , 71 ],

` Name` : [ `Sam` , `Andrea` , `Alex` , ` Robin` , `Kia` ],

  `Age` : [ 14 , 25 , 55 , 8 , 21 ]})

  
# Create index

index_ = pd.date_range ( `2010-10-09 08:45` , periods = 5 , freq = `H` )

 
# Set index

df.index = index_

 
# Print DataFrame

print (df)

Exit:

We will now use DataFrame.truncate () for DataFrame.truncate () records up to & # 39; 2010-10-09 09: 45: 00 & # 39; and after & # 39; 2010-10-09 11: 45: 00 & # 39; in the specified data frame.

# return a truncated data frame

result = df.truncate (before = ` 2010-10-09 09: 45: 00` , after = `2010-10-09 11: 45: 00` )

  
# Print the result

print (result)

Output:

As we can see in the output, DataFrame.truncate () successfully DataFrame.truncate () write before and after passed labels in this data frame.

Example # 2: Use DataFrame.truncate () to DataFrame.truncate () some entries before and after the passed labels of this data frame.

# import pandas as pd

import pandas as pd

 
# Create DataFrame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ], 

"B" : [ 7 , 2 , 54 , 3 , None ], 

"C" : [ 20 , 16 , 11 , 3 , 8 ], 

"D" : [ 14 , 3 , None , 2 , 6 ]}) 

 
# Create Index

index_ = [ `Row_1` , `Row_2` , ` Row_3` , `Row_4` , `Row_5` ]

  
# Set index

df.index = index_

  
# Print DataFrame

print (df )

Output:

Now we will use DataFrame.truncate () to trim records to & # 39; Row_3 & # 39; and after & # 39; Row_4 & # 39; in this data frame.

# return a truncated data frame

result = df.truncate (before = ` Row_3` , after = `Row_4` )

 
# Print result

print (result)

Output:

As we can see in the output, DataFrame.truncate () successfully DataFrame.truncate () writes before and after the transmitted labels in this frame d data.

Get Solution for free from DataCamp guru