gpt4 book ai didi

pandas - 根据列上的值展平数据框的最佳方法

转载 作者:行者123 更新时间:2023-12-04 00:34:13 25 4
gpt4 key购买 nike

我必须处理包含数十万行的整个数据帧,但我可以将其简化如下:

df = pd.DataFrame([
('a', 1, 1),
('a', 0, 0),
('a', 0, 1),
('b', 0, 0),
('b', 1, 0),
('b', 0, 1),
('c', 1, 1),
('c', 1, 0),
('c', 1, 0)
], columns=['A', 'B', 'C'])

print (df)

A B C
0 a 1 1
1 a 0 0
2 a 0 1
3 b 0 0
4 b 1 0
5 b 0 1
6 c 1 1
7 c 1 0
8 c 1 0

我的目标是根据“A”列中的标签来展平“B”和“C”列
   A  B_1  B_2  B_3  C_1  C_2  C_3
0 a 1 0 0 1 0 1
3 b 0 1 0 0 0 1
6 c 1 1 1 1 0 0

我写的代码给出了我想要的结果,但它非常慢,因为它在唯一标签上使用了一个简单的 for 循环。
我看到的解决方案是编写一些优化我的代码的矢量化函数。有人有什么想法吗?
下面我附上代码。
added_col = ['B_1', 'B_2', 'B_3', 'C_1', 'C_2', 'C_3']

new_df = df.drop(['B', 'C'], axis=1).copy()
new_df = new_df.iloc[[x for x in range(0, len(df), 3)], :]
new_df = pd.concat([new_df,pd.DataFrame(columns=added_col)], sort=False)

for e, elem in new_df['A'].iteritems():
new_df.loc[e, added_col] = df[df['A'] == elem].loc[:,['B','C']].T.values.flatten()

最佳答案

这是一种方法:

# create a row number by group
df['rn'] = df.groupby('A').cumcount() + 1

# pivot the table
new_df = df.set_index(['A', 'rn']).unstack()

# rename columns
new_df.columns = [x + '_' + str(y) for (x, y) in new_df.columns]

new_df.reset_index()
# A B_1 B_2 B_3 C_1 C_2 C_3
#0 a 1 0 0 1 0 1
#1 b 0 1 0 0 0 1
#2 c 1 1 1 1 0 0

关于pandas - 根据列上的值展平数据框的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com