【发布时间】:2019-08-20 19:15:21
【问题描述】:
我对大数据框有疑问 *大约 1kk 行,180 列。它从 3 列开始。第一列包含 id。第二和第三包含每行中的列表-它们是连接的(第一行-第一列列表中的第一个元素与第二列列表中的第一个元素连接:
ids | fruits | count |
1 | [grape, apple, banana] | [7.0, 4.0, 3.0]
2 | [mango, banana, strawberry, grape] | [5.0, 8.0, 15.0, 2.0]
3 | [apple, avocado] | [9.0, 1.0]
4 | NaN | NaN
5 | [pummelo] | [12.0]
我想使用“fruits”列中的列表元素,作为新列的名称,这些列将具有分配给行和水果的值。但是没有重复的列,就像这样:
ids | grape | apple | banana | mango | strawberry | avocado | pummelo
1 | 7.0 | 4.0 | 3.0 | NaN | NaN | NaN | NaN
2 | 2.0 | NaN | 8.0 | 5.0 | 15.0 | NaN | NaN
3 | NaN | 9.0 | NaN | NaN | NaN | 1.0 | NaN
4 | NaN | NaN | NaN | NaN | NaN | NaN | NaN
5 | NaN | NaN | NaN | NaN | NaN | NaN | 12.0
集合中唯一元素的数量(所有列表的非重复总和)“水果”为 180,这就是为什么最后我想要 180 列。
问题是速度。我尝试了 pandas iterrows(),但是当涉及到所有 1kk 行时,这将成为无休止的故事。下面是我尝试过的代码。
#making an example dataframe
import numpy as np
fruit_df = pd. DataFrame(columns=['ids','fruits','count'])
ids = [1,2,3,4,5]
fruits = [['grape', 'apple', 'banana'], ['mango', 'banana', 'strawberry', 'grape'], ['apple', 'avocado'], np.nan, ['pummelo']]
count = [[7.0, 4.0, 3.0],[5.0, 8.0, 15.0, 2.0], [9.0, 1.0], np.nan, [12.0]]
#creating fruits columns in dataframe - this one timing is ok , fine for me (about 15 mins)
fruits_columns=[]
for row in fruit_df['fruits']:
if type(row)==list:
fruits_columns.append(row)
else:
fruits_columns.append(list())
import itertools
all_fruits = list(itertools.chain(*fruits_columns))
all_fruits = set(all_fruits)
for fruit in all_fruits:
fruit_df[fruit]=np.nan
#iterating over the data - here is main problem - takes very, very long time.. works well for this tiny dataset but when it comes to 1000000 rows and 180 columns...
def iter_over_rows(data):
for index, row in data.iterrows():
if type(row['fruits'])!=float:
for cat in range(len(row['fruits'])):
data[row['fruits'][cat]][index] = row['count'][cat]
我想加快这个数据处理的速度。想过用所有 180 种水果作为键来制作字典,它们算作价值——但最终订单会被损坏。如果您知道如何更快地做到这一点,那就太好了。干杯!
【问题讨论】:
标签: python python-3.x pandas list time