【问题标题】:Explode a row to multiple rows in pandas dataframe在熊猫数据框中将一行分解为多行
【发布时间】:2017-02-12 16:18:14
【问题描述】:

我有一个带有以下标头的数据框:

id, type1, ..., type10, location1, ..., location10

我想将其转换如下:

id, type, location 

我设法使用嵌入式 for 循环来做到这一点,但它非常慢:

new_format_columns = ['ID', 'type', 'location'] 
new_format_dataframe = pd.DataFrame(columns=new_format_columns)



print(data.head())
new_index = 0 
for index, row in data.iterrows(): 
        ID = row["ID"]

        for i in range(1,11):
                if row["type"+str(i)] == np.nan:
                        continue
                else:
                        new_row = pd.Series([ID, row["type"+str(i)], row["location"+str(i)]])
                        new_format_dataframe.loc[new_index] = new_row.values
                        new_index += 1

对使用原生 pandas 功能的改进有何建议?

【问题讨论】:

  • 你的数据集有多大?
  • @MMF 现在几 GB

标签: python pandas explode reshape melt


【解决方案1】:

你可以使用lreshape:

types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]

print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))

示例:

import pandas as pd

df = pd.DataFrame({
'type1': {0: 1, 1: 4}, 
'id': {0: 'a', 1: 'a'}, 
'type10': {0: 1, 1: 8},
'location1': {0: 2, 1: 9},
'location10': {0: 5, 1: 7}})

print (df)
  id  location1  location10  type1  type10
0  a          2           5      1       1
1  a          9           7      4       8

types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]

print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))
  id  Location  Type
0  a         2     1
1  a         9     4
2  a         5     1
3  a         7     8

另一个双melt的解决方案:

print (pd.concat([pd.melt(df, id_vars='id', value_vars=types, value_name='type'),
                  pd.melt(df, value_vars=location, value_name='Location')], axis=1)
         .drop('variable', axis=1))

  id  type  Location
0  a     1         2
1  a     4         9
2  a     1         5
3  a     8         7

编辑:

lreshape 现在没有记录,但将来可能会被删除 (with pd.wide_to_long too)。

可能的解决方案是将所有 3 个功能合并为一个 - 可能是 melt,但现在尚未实施。也许在一些新版本的熊猫中。然后我的答案会更新。

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2018-11-16
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多