在具有相同条件的多列中切片字符串

Slice string in multiple column with same condition

我有多个列需要以相同的条件进行切片我可以看到一些解决方案 here 但它们不适用于多个列

df['x', 'y']=df['x', 'y'].str.slice(0,19)

错误

AttributeError: 'DataFrame' object has no attribute 'str'

您需要使用 apply 函数将其应用于多个列:

df[['x','y']]=df[['x','y'].apply(lambda x:x.str.slice(0,19))

它应该给出正确的输出。

您可以使用applymap()方法

import pandas as pd

df_exp = pd.DataFrame([('ABCDEF', 'GHIJKL')], columns=["x", "y"])

print(df_exp.head(10))
#         x       y
# 0  ABCDEF  GHIJKL

your_slice_func = lambda x: x[0:3]
df_result = df_exp.applymap(your_slice_func)

print(df_result.head(10))
#      x    y
# 0  ABC  GHI