📜  如何就地使用 Pandas apply()?

📅  最后修改于: 2022-05-13 01:55:17.131000             🧑  作者: Mango

如何就地使用 Pandas apply()?

在本文中,我们将了解如何在Python中就地使用 Pandas apply()。

在Python中,此函数等效于 map()函数。它将一个函数作为输入并将其应用于整个 DataFrame。如果您正在处理表格形式的数据,则需要选择您的函数应该作用于哪个轴(0 表示列;1 表示行)。

pandas apply() 方法是否有就地参数?

不,apply() 方法不包含就地参数,这与这些具有就地参数的 pandas 方法不同:

  • df.drop()
  • df.rename(就地=真)
  • 填充()
  • 下降()
  • 排序值()
  • 重置索引()
  • 排序索引()
  • 改名()

就地参数实际上是什么意思?

当 inplace = True 时,数据在原地编辑,这意味着它将不返回任何内容,并且将更新数据框。当 inplace = False(默认值)时,执行操作并返回对象的副本。

示例 1:为一列就地应用()

在下面的代码中。我们首先导入 pandas 包并使用 pd.read_csv() 导入我们的 CSV 文件。导入后,我们在数据框的“体验”列上使用应用函数。我们将该列的字符串转换为大写。

使用的 CSV 文件:

Python3
# code
import pandas as pd
  
# importing our dataset
df = pd.read_csv('hiring.csv')
# viewing the dataFrame
print(df)
  
# we change the case of all the strings
# in experience column to uppercase
df['experience'] = df['experience'].apply(str.upper)
  
# viewing the modified column
print(df['experience'])


Python3
import pandas as pd
import numpy as np
  
# importing our dataset
data = pd.read_csv('cluster_blobs.csv')
  
# viewing the dataFrame
print(df)
  
# we convert the datatype of columns from float to int.
data[['X1', 'X2']] = data[['X1', 'X2']].apply(np.int64)
  
# viewing the modified column
print(data[['X1', 'X2']])


Python3
import pandas as pd
import numpy as np
  
# importing our dataset
data = pd.read_csv('cluster_blobs.csv')
  
# viewing the dataFrame
print(data)
  
# we convert the datatype of
# columns from float to int.
data = data.apply(np.int64)
  
# viewing the modified column
print(data)


输出:

0      FIVE
1       TWO
2     SEVEN
3     THREE
4    ELEVEN
Name: experience, dtype: object

示例 2:针对多列就地应用()

在此示例中,我们在多个列上使用 apply() 方法。我们将列的数据类型从 float 更改为 int。使用的 CSV 文件点击这里。

Python3

import pandas as pd
import numpy as np
  
# importing our dataset
data = pd.read_csv('cluster_blobs.csv')
  
# viewing the dataFrame
print(df)
  
# we convert the datatype of columns from float to int.
data[['X1', 'X2']] = data[['X1', 'X2']].apply(np.int64)
  
# viewing the modified column
print(data[['X1', 'X2']])

输出:

示例 3:为所有列就地应用()。

在此示例中,我们使用与之前相同的 CSV 文件。这里我们对整个数据框使用 apply() 方法。我们将列的数据类型从 float 更改为 int。

Python3

import pandas as pd
import numpy as np
  
# importing our dataset
data = pd.read_csv('cluster_blobs.csv')
  
# viewing the dataFrame
print(data)
  
# we convert the datatype of
# columns from float to int.
data = data.apply(np.int64)
  
# viewing the modified column
print(data)

输出: