在寻找一种在循环内将一列拆分为多列的方法时,我偶然发现了 a list of useful Pandas snippets包含这个表达式:
# Split delimited values in a DataFrame column into two new columns
df['new_col1'], df['new_col2'] = zip(*df['original_col'].apply(lambda x: x.split(': ', 1)))
它工作得很好,但我无法理解它是如何运作的,特别是关于 * 符号。到目前为止,我只在函数定义中看到星号,并且无法找到有关此情况的任何文档。
谁能解释一下它是如何工作的吗?
最佳答案
zip() in conjunction with the * operator can be used to unzip a list:
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print zipped
输出:
[(1, 4), (2, 5), (3, 6)]
说明:
它从列表中获取值:x
和 y
(按列)并将其保存在元组中。
并且(这是您感兴趣的部分):
x2, y2 = zip(*zipped)
print x2
print y2
输出:
(1, 2, 3)
(4, 5, 6)
说明:
- zip 解压
zipped
的内容(从列表中取出内容) - 从列中的每个元组中获取值,并将其保存在元组中。
因此,如果我们将这些元组放入列中(在解压之前),它们将如下所示:
[
(1, 4)
(2, 5)
(3, 6)
]
打开包装后,它们将如下所示:
(1, 4)
(2, 5)
(3, 6)
如果你看到的话,第一列有 1、2 和 3。第二列有 4、5、6
这就是 zip
与 *
运算符结合使用的效果。
关于Python-Pandas : meaning of asterisk sign in expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802940/