python - 从具有列表元素的系列创建堆叠的 Pandas 系列

标签 python pandas

我有一个包含元素列表的 Pandas 系列:

import pandas as pd
s = pd.Series([ ['United States of America'],['China', 'Hong Kong'], []])
print(s)

0    [United States of America]
1            [China, Hong Kong]
2                            []

如何获得如下系列:

0 United States of America
1 China
1 Hong Kong

我不确定 2 会发生什么。

最佳答案

以下选项均返回 Series。创建一个新框架并列出。

pd.DataFrame(s.tolist()).stack()

0  0    United States of America
1  0                       China
   1                   Hong Kong
dtype: object

要重置索引,请使用

pd.DataFrame(s.tolist()).stack().reset_index(drop=True)

0    United States of America
1                       China
2                   Hong Kong
dtype: object

要转换为 DataFrame,请调用 to_frame()

pd.DataFrame(s.tolist()).stack().reset_index(drop=True).to_frame('countries')

                  countries
0  United States of America
1                     China
2                 Hong Kong

如果您正在尝试编写高尔夫代码,请使用

sum(s, [])
# ['United States of America', 'China', 'Hong Kong']

pd.Series(sum(s, []))

0    United States of America
1                       China
2                   Hong Kong
dtype: object

甚至,

pd.Series(np.sum(s))

0    United States of America
1                       China
2                   Hong Kong
dtype: object

但是,与大多数其他涉及列表求和操作的操作一样,这在性能方面很糟糕(列表串联操作效率低下)。


使用 itertools.chain 链接可以实现更快的操作:

from itertools import chain
pd.Series(list(chain.from_iterable(s)))

0    United States of America
1                       China
2                   Hong Kong
dtype: object

pd.DataFrame(list(chain.from_iterable(s)), columns=['countries'])

                  countries
0  United States of America
1                     China
2                 Hong Kong

关于python - 从具有列表元素的系列创建堆叠的 Pandas 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54739886/

相关文章:

python - 创建一个空的 Pandas DataFrame,然后填充它

python - 将文本添加到 pandas dataframe plot

python - 如何通过 'Exclude' 条件创建行并扩展到现有的 Dataframe 中?

python - 将最大值时间戳放入 PySpark 的数组中

python - 在 Python 中组合 3 个 bool 掩码

Python3 input() 的奇怪行为

Python 3 XChaCha20 测试向量可用于加密,但解密阶段失败

使用自签名证书的 Python https 连接

python - 在循环中跳过多次迭代

python - 计算一个单词中出现的字母到 pandas DataFrame