将列中的值用作另一列pandas的字符串切片机
我正在尝试将单元格值用作新列中字符串的切片。例如,如果我创建此表。
data = pd.DataFrame(data = {'Name':['This is a title'], 'Number':[-5]})
Name Number
0 This is a title -5
并创建一个类似的新列:
data['Test'] = data.Name.str[:data.Number.item()]
它将创建新的列,如预期:
Name Number Test
0 This is a title -5 This is a
当我的行超过行时发生问题,因此,如果我创建下表:
data = pd.DataFrame(data = {'Name':['This is a title', 'This is another title'], 'Number':[-5, -13]})
Name Number
0 This is a title -5
1 This is another title -13
“测试”列的创建产生:
can only convert an array of size 1 to a Python scalar
我理解为什么这是因为该列现在具有多个值以来,我想知道的是如何使用具有多个行以上的数据框架来执行此操作?我尝试了.items(),.values()等。新列只是NAN。
有什么想法吗?
谢谢!
I'm trying to use a cell value as the slice for a string in a new column. For example, if I create this table.
data = pd.DataFrame(data = {'Name':['This is a title'], 'Number':[-5]})
Name Number
0 This is a title -5
And create a new column like so:
data['Test'] = data.Name.str[:data.Number.item()]
It'll create the new column, as expected:
Name Number Test
0 This is a title -5 This is a
The issue occurs when I have more than row, so if I create the following table:
data = pd.DataFrame(data = {'Name':['This is a title', 'This is another title'], 'Number':[-5, -13]})
Name Number
0 This is a title -5
1 This is another title -13
The creation of the 'Test' column yields:
can only convert an array of size 1 to a Python scalar
I understand why this is happening since the column now has more than one value, what I want to know is how can I do this with a dataframe that has more than one row? I've tried .items(), .values(), etc. and the new column just becomes NaN.
Any thoughts?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
使用
与axis = 1
使用,然后按dataframe
行进。输出:
You can use
apply
withaxis=1
and move ondataframe
row by row.Output:
不幸的是,在这里,您需要循环。列表理解将是最有效的:
输出:
Unfortunately, here, you need to loop. A list comprehension will be the most efficient:
output: