如何在 Pandas 中使用轴 = 0 和轴 = 1?
在本文中,我们将讨论如何使用Python在 pandas 中使用 axis=0 和 axis=1 。
有时我们只需要对行进行操作,有时只对列进行操作,在这种情况下,我们指定轴参数。在本文中,让我们看几个示例来了解何时以及如何使用轴参数。在 pandas 中,axis = 0 表示水平轴或行,axis = 1 表示垂直轴或列。
轴=0
在执行特定操作时将轴设置为零时,将对满足条件的行执行操作。
使用的数据集:
示例:使用轴=0
Python3
# importing packages
import pandas as pd
# importing our dataset
df = pd.read_csv('hiring.csv')
# dropping the column named 'experience'
df = df.drop([0, 3], axis=0)
# 'viewing the dataframe
df.head()
Python3
# importing packages
import pandas as pd
# creating a dataset
df = pd.DataFrame([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]],
columns=['a', 'b', 'c'])
# viewing the dataFrame
print(df)
# finding mean by rows
df.mean(axis='rows')
Python3
# importing packages
import pandas as pd
# importing our dataset
df = pd.read_csv('hiring.csv')
# dropping the column named 'experience'
df = df.drop(['experience'], axis=1)
# 'viewing the dataframe
df.head()
Python3
# importing packages
import pandas as pd
# creating a dataset
df = pd.DataFrame([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]],
columns=['a', 'b', 'c'])
# viewing the dataFrame
print(df)
# finding mean by columns
df.mean(axis='columns')
输出:
示例:使用轴=0
Python3
# importing packages
import pandas as pd
# creating a dataset
df = pd.DataFrame([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]],
columns=['a', 'b', 'c'])
# viewing the dataFrame
print(df)
# finding mean by rows
df.mean(axis='rows')
输出:
轴=1
在执行特定操作时将轴设置为 1 时,将对满足条件的列执行操作。
示例:使用轴=1
Python3
# importing packages
import pandas as pd
# importing our dataset
df = pd.read_csv('hiring.csv')
# dropping the column named 'experience'
df = df.drop(['experience'], axis=1)
# 'viewing the dataframe
df.head()
输出:
示例:使用轴=1
Python3
# importing packages
import pandas as pd
# creating a dataset
df = pd.DataFrame([[1, 2, 3], [4, 5, 6],
[7, 8, 9], [10, 11, 12]],
columns=['a', 'b', 'c'])
# viewing the dataFrame
print(df)
# finding mean by columns
df.mean(axis='columns')
输出: