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

2024-05-13 17:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫系列的元素列表:

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会发生什么。你知道吗


Tags: ofimport元素pandas列表asunitedseries
3条回答

以下选项全部返回序列。创建新框架并列表化。你知道吗

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

要转换为数据帧,请调用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

或使用:

df = pd.DataFrame(s.tolist())
print(df[0].fillna(df[1].dropna().item()))

输出:

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

假设这是一个列表

pd.Series(s.sum())
Out[103]: 
0    United States of America
1                       China
2                   Hong Kong
dtype: object

相关问题 更多 >