如何保留 pd df 每行的 n 个字符,其中 n 因行而异?

How to keep n characters of each row of a pd df, where n differs by row?

我创建了一个 df,其中一列包含我想要 trim 每次基于不同 int 值的字符串值。 前任。: 来自:

length String
-3 adcdef
-5 ghijkl

我想得到:

length String
-3 def
-5 hijkl

我试过的是:

for i in range(len(df.index)):
    val = df['string'].iloc[i]
    n = df['length'].iloc[i]
    df['string'].iloc[i] = val[n:]

但是,我不断收到此警告:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

关于如何避免得到它的任何想法?

谢谢!

试试 apply:

df["String"] = df.apply(lambda x: x["String"][x["lenght"]:], axis=1)

>>> df
   lenght String
0      -3    def
1      -5  hijkl