简体   繁体   English

使用列表列表在 Pandas 中创建 DataFrame

[英]creating a DataFrame in pandas using a List of lists

I have a list of lists like this.我有一个像这样的列表。

 sports =  [['Sport', 'Country(s)'], ['Foot_ball', 'brazil'], ['Volleyball', 'Argentina', 'India'], ['Rugger', 'New_zealand', ‘South_africa’], ['Cricket', 'India'], ['Carrom', 'Uk', ‘Usa’], ['Chess', 'Uk']]

I want to create panda data frame using the above lists as follows:我想使用上面的列表创建熊猫数据框,如下所示:

sport      Country(s)
Foot_ball      brazil
Volleyball     Argentina   
Volleyball     india
Rugger         New_zealnd  
Rugger         South_africa
Criket         India
Carrom         UK
Carrom         Usa
Chess          UK

I was trying like this我是这样尝试的

sport_x = []
for x in sports[1:]:
    sport_x.append(x[0])
print(sport_x)

country = []
for y in sports[1:]:
    country.append(y[1:])

header = sports[0]

df = pd.DataFrame([sport_x,country], columns = header)

halfway through, im getting this error But i was getting this error.中途,我收到此错误但我收到此错误。

AssertionError: 2 columns passed, passed data had 6 columns

Any suggestions, how to do this.任何建议,如何做到这一点。

Something like this to first "expand" the irregularly shaped rows, then dataframefy them.像这样的东西首先“扩展”不规则形状的行,然后对它们进行数据框化。

>>> sports = [
        ["Sport", "Country(s)"],
        ["Foot_ball", "brazil"],
        ["Volleyball", "Argentina", "India"],
        ["Rugger", "New_zealand", "South_africa"],
        ["Cricket", "India"],
        ["Carrom", "Uk", "Usa"],
        ["Chess", "Uk"],
    ]
>>> expanded_sports = []
>>> for row in sports:
...   for country in row[1:]:
...     expanded_sports.append((row[0], country))
...
>>> pd.DataFrame(expanded_sports[1:], columns=expanded_sports[0])
        Sport    Country(s)
0   Foot_ball        brazil
1  Volleyball     Argentina
2  Volleyball         India
3      Rugger   New_zealand
4      Rugger  South_africa
5     Cricket         India
6      Carrom            Uk
7      Carrom           Usa
8       Chess            Uk
>>>

EDIT : Another solution using .melt() , but this looks uglier to me, and the order isn't the same.编辑:另一个使用.melt()解决方案,但这对我来说看起来更丑,而且顺序也不一样。

>>> pd.DataFrame(sports[1:]).melt(0, value_name='country').dropna().drop('variable', axis=1).rename({0: 'sport'}, axis=1)
         sport       country
0    Foot_ball        brazil
1   Volleyball     Argentina
2       Rugger   New_zealand
3      Cricket         India
4       Carrom            Uk
5        Chess            Uk
7   Volleyball         India
8       Rugger  South_africa
10      Carrom           Usa

Or, pandas way using explode and list comprehension:或者,熊猫使用explode和列表理解的方式:

df=pd.DataFrame([[i[0],','.join(i[1:])] if len(i)>2 else i for i in sports[1:]],
         columns=sports[0])
df['Country(s)']=df['Country(s)'].str.split(',')
final=df.explode('Country(s)').reset_index(drop=True)

        Sport    Country(s)
0   Foot_ball        brazil
1  Volleyball     Argentina
2  Volleyball         India
3      Rugger   New_zealand
4      Rugger  South_africa
5     Cricket         India
6      Carrom            Uk
7      Carrom           Usa
8       Chess            Uk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM