使用 Pandas Python 将嵌套列表转换为数据框
Convert nested list to a dataframe using Pandas Python
我有以下嵌套列表:
lisA = [['Monday', ['Cherry', 'Mango']],
['Tuesday', ['Blueberry', 'Apple', 'Grape']],
['Wednesday', ['Apple', 'Orange']],
['Thursday', ['Watermelon', 'Kiwi', 'Apple']],
['Friday', ['Orange', 'Cherry']]]
我需要将这个嵌套列表转换为如下所示的数据框:
| Day | Item |
| -------- | -------------- |
| Monday | Cherry |
| Monday | Mango |
|Tuesday | Blueberry |
|Tuesday | Apple |
|Tuesday | Grape |
|Wednesday | Apple |
|Wednesday | Orange |
|Thursday | Watermelon |
|Thursday | Kiwi |
|Thursday | Apple |
|Friday | Orange |
|Friday | Cherry |
如果我使用下面的代码将嵌套列表转换为数据框,我会在一列中得到星期一,在另一列中得到整个星期一列表
pd.DataFrame(lisA)
将嵌套列表 (lisA) 转换为上面显示的数据框的最佳方法是什么?
你可以试试
df = (pd.DataFrame(lisA, columns=['Day', 'Item'])
.explode('Item', ignore_index=True))
print(df)
Day Item
0 Monday Cherry
1 Monday Mango
2 Tuesday Blueberry
3 Tuesday Apple
4 Tuesday Grape
5 Wednesday Apple
6 Wednesday Orange
7 Thursday Watermelon
8 Thursday Kiwi
9 Thursday Apple
10 Friday Orange
11 Friday Cherry
我有以下嵌套列表:
lisA = [['Monday', ['Cherry', 'Mango']],
['Tuesday', ['Blueberry', 'Apple', 'Grape']],
['Wednesday', ['Apple', 'Orange']],
['Thursday', ['Watermelon', 'Kiwi', 'Apple']],
['Friday', ['Orange', 'Cherry']]]
我需要将这个嵌套列表转换为如下所示的数据框:
| Day | Item |
| -------- | -------------- |
| Monday | Cherry |
| Monday | Mango |
|Tuesday | Blueberry |
|Tuesday | Apple |
|Tuesday | Grape |
|Wednesday | Apple |
|Wednesday | Orange |
|Thursday | Watermelon |
|Thursday | Kiwi |
|Thursday | Apple |
|Friday | Orange |
|Friday | Cherry |
如果我使用下面的代码将嵌套列表转换为数据框,我会在一列中得到星期一,在另一列中得到整个星期一列表
pd.DataFrame(lisA)
将嵌套列表 (lisA) 转换为上面显示的数据框的最佳方法是什么?
你可以试试
df = (pd.DataFrame(lisA, columns=['Day', 'Item'])
.explode('Item', ignore_index=True))
print(df)
Day Item
0 Monday Cherry
1 Monday Mango
2 Tuesday Blueberry
3 Tuesday Apple
4 Tuesday Grape
5 Wednesday Apple
6 Wednesday Orange
7 Thursday Watermelon
8 Thursday Kiwi
9 Thursday Apple
10 Friday Orange
11 Friday Cherry