[英]Creating a new column and rows in dataframe pyspark
I have a dataframe like this 我有一个这样的数据框
id_1 id_desc cat_1 cat_2
111 ask ele phone
222 ask hr ele phone
333 ask hr dk ele phone
444 askh ele phone
If cat_1
, cat_2
are same for multiple id_1
, that association need to be captured as a new column. 如果
cat_1
, cat_2
对于多个id_1
相同,则需要将该关联捕获为新列。
Need an output like this, 需要这样的输出,
id_1 id_desc cat_1 cat_2 id_2
111 ask ele phone 222
111 ask ele phone 333
111 ask ele phone 444
222 ask hr ele phone 111
222 ask hr ele phone 333
222 ask hr ele phone 444
333 ask hr dk ele phone 111
333 ask hr dk ele phone 222
333 ask hr dk ele phone 444
how to get this done in python? 如何在python中做到这一点?
I wasn't able to come up with anything particularly elegant, but this should get the job done: 我无法提出任何特别优雅的方法,但这应该可以完成工作:
import pandas as pd
import numpy as np
df = pd.DataFrame([[111, 'ask', 'ele', 'phone'],
[222, 'ask_hr', 'ele', 'phone'],
[333, 'ask_hr_dk', 'ele', 'phone'],
[444, 'askh', 'ele', 'phone']],
columns=['id_1', 'id_desc', 'cat_1', 'cat_2'])
grouped = df.groupby(by=['cat_1', 'cat_2']) # group by the columns you want to be identical
data = [] # a list to store all unique groups
# In your example, this loop is not needed, but this generalizes to more than 1 pair
# of cat_1 and cat_2 values
for group in grouped.groups:
n_rows = grouped.get_group(group).shape[0] # how many unique id's in a group
all_data = np.tile(grouped.get_group(group).values, (n_rows, 1)) # tile the data n_row times
ids = np.repeat(grouped.get_group(group)['id_1'].values, n_rows) # repeat the ids n_row times
data += [np.c_[all_data, ids]] # concat the two sets of data and add to list
df_2 = pd.DataFrame(np.concatenate(data), columns=['id_1', 'id_desc', 'cat_1', 'cat_2', 'id_2'])
The basic idea is to group your data by the cat_1
and cat_2
columns (using groupby
), use np.tile
to create copies of each group as many times as there are unique values of id_1
in the group, and concatenate the result with the unique id_1
values (one value per group of data). 基本思想是按
cat_1
和cat_2
列对数据进行cat_1
(使用groupby
),使用np.tile
创建每个组的副本的次数要id_1
该组中id_1
唯一值,然后将结果与唯一id_1
值(每组数据一个值)。
If you don't want id_1
to ever be the same as id_2
, just select the rows where they don't match: 如果您不希望
id_1
与id_2
相同,则只需选择不匹配的行:
df_2 = df_2[df_2['id_1'] != df_2['id_2']]
And if you want them sorted on id_1
: 如果希望它们在
id_1
上id_1
:
df_2.sort_values('id_1', inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.