在我的 Pandas DataFrame 的一列中,我有一些字符串,其长度需要限制为同一数据帧中另一列中存在的值。
我尝试创建一个新列并使用普通的 python 字符串索引,并将另一列作为值。
这是我尝试运行的代码的 MWE:
import pandas as pd
data = [[5, 'LONSTRING'], [3, 'LONGERSTRING'], [7, 'LONGESTSTRINGEVER']]
df = pd.DataFrame(data, columns=['String Limit', 'String'])
df['Short String'] = df['String'][:df['String Limit']]
print(df)
我期望一个包含较短字符串的新列:
String Limit String Short String
0 5 LONSTRING LONST
1 3 LONGERSTRING LON
2 7 LONGESTSTRINGEVER LONGEST
相反,我得到了一个类型错误:
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [0 5
1 3
2 7
Name: String Limit, dtype: int64] of <class 'pandas.core.series.Series'>
字符串索引似乎不能这样完成,因为df['String Limit']
是整个系列而不仅仅是一行值 - 但有没有其他方法可以做到这一点?
最佳答案
问题是您需要单独过滤所有值,因此请使用 DataFrame.apply
使用 axis=1
按行循环:
df['Short String'] = df.apply(lambda x: x['String'][:x['String Limit']], axis=1)
或者使用 zip
进行列表理解:
df['Short String'] = [x[:y] for x, y in zip(df['String'], df['String Limit'])]
<小时/>
print(df)
String Limit String Short String
0 5 LONSTRING LONST
1 3 LONGERSTRING LON
2 7 LONGESTSTRINGEVER LONGEST
关于python - 使用其他列的索引值在 pandas 数据框中的一列中进行字符串索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57425987/