将空列添加到pandas DataFrame对象的最简单方法是什么?我偶然发现的最好的就像是
df['foo'] = df.apply(lambda _: '', axis=1)
Run Code Online (Sandbox Code Playgroud)
是否有一种不那么不正常的方法?
我有一个处理DataFrame的函数,主要是将数据处理成桶,在特定列中使用创建二进制矩阵的特征pd.get_dummies(df[col]).
为了避免一次使用此函数处理我的所有数据(内存不足并导致iPython崩溃),我使用以下方法将大型DataFrame分解为块:
chunks = (len(df) / 10000) + 1
df_list = np.array_split(df, chunks)
Run Code Online (Sandbox Code Playgroud)
pd.get_dummies(df)会自动创建一个基于内容的新栏目df[col]和这些都有可能为每个不同df在df_list.
处理完毕后,我使用以下方法将DataFrame连接在一起:
for i, df_chunk in enumerate(df_list):
print "chunk", i
[x, y] = preprocess_data(df_chunk)
super_x = pd.concat([super_x, x], axis=0)
super_y = pd.concat([super_y, y], axis=0)
print datetime.datetime.utcnow()
Run Code Online (Sandbox Code Playgroud)
第一个块的处理时间是完全可以接受的,然而,它每块增长!这与它没有关系,preprocess_data(df_chunk)因为没有理由增加它.由于呼叫的结果,是否会增加时间pd.concat()?
请参阅下面的日志:
chunks 6
chunk 0
2016-04-08 00:22:17.728849
chunk 1
2016-04-08 00:22:42.387693
chunk 2
2016-04-08 00:23:43.124381
chunk 3
2016-04-08 00:25:30.249369
chunk 4
2016-04-08 00:28:11.922305
chunk 5
2016-04-08 00:32:00.357365 …Run Code Online (Sandbox Code Playgroud) python performance concatenation processing-efficiency pandas
我在这个线程中读到:
pandas DataFrame.join 的运行时间是多少(大“O”顺序)?
内连接预计为 O(n),而左连接和右连接预计为 O(n log n)。我一直在使用随机数据帧进行一些测试,例如:
df1 = pd.DataFrame({
'user_id': range(1, size + 1), # Unique user_id for df1
'numeric_1': np.random.rand(size),
'numeric_2': np.random.rand(size),
'numeric_3': np.random.rand(size),
'string_1': np.random.choice(['A', 'B', 'C', 'D'], size),
'string_2': np.random.choice(['E', 'F', 'G', 'H'], size),
'string_3': np.random.choice(['I', 'J', 'K', 'L'], size),
})
df2 = pd.DataFrame({
'user_id': range(size + 1, 2 * size + 1), # Ensuring unique user_id for df2
'numeric_4': np.random.rand(size),
'numeric_5': np.random.rand(size),
'numeric_6': np.random.rand(size),
'string_4': np.random.choice(['M', 'N', 'O', 'P'], size),
'string_5': np.random.choice(['Q', 'R', …Run Code Online (Sandbox Code Playgroud)