![](/img/trans.png)
[英]new column in pandas DataFrame based on unique values (lists) of an existing column
[英]Pandas - consolidating rows based on unique values in column of lists
我想通過將“值”列中的值折疊為每個id的唯一值的單個列表,將一列中具有重復值的數據框轉換為合並的數據框。 “值”列中的值已從“文本”列中提取,並且每個id的文本被分成多行,其中一個文本元素中的單詞也可以出現在另一文本元素中。 因此,這些值可能會出現在多個文本元素中,因此會被記錄多次。
這是起始數據幀的子集(約200萬行):
id text value
0 a text 123 text [123]
1 a text abc text foo bar [abc, foo, bar]
2 a text foo bar text [foo, bar]
3 b text xyz text [xyz]
4 b text []
5 b text 456 text [456]
我想將上面的數據框轉換為下面的數據框,並且可以從文本字段中丟失信息。
id text value
0 a text 123 text [123, abc, foo, bar]
1 b text xyz text [xyz, 456]
我正在尋找一個將列表拆分為行,將分離出的列與入門數據pd.melt
合並,然后使用pd.melt
。 最后一步需要花費很長時間,但可能是必要的,因為我有另一個包含每個值信息的數據框,並且我想使用“值”列作為鍵來合並這兩個數據框。 但是我不認為列表中有多個ID可以做到嗎?
value info
0 123 info1
1 456 info2
2 abc info3
3 foo info4
4 bar info5
5 xyz info6
中介目標:
id text value
0 a text 123 text 123
1 b text xyz text xyz
2 a text 123 text abc
3 b text xyz text 456
4 a text 123 text foo
6 a text 123 text bar
最終目標:
id text value info
0 a text 123 text 123 info1
1 a text 123 text 456 info2
2 a text 123 text abc info3
3 a text 123 text foo info4
4 b text xyz text bar info5
5 b text xyz text xyz info6
我正在使用agg
並first
將list
組合用於df,然后進行unnesting
,然后合並
s=df.groupby('id').agg({'text':'first','value': lambda x : list(set(x.sum()))})
unnesting(s.reset_index(),['value']).merge(df1,on='value')
Out[307]:
value id text info
0 abc a text 123 text info3
1 foo a text 123 text info4
2 123 a text 123 text info1
3 bar a text 123 text info5
4 456 b text xyz text info2
5 xyz b text xyz text info6
def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.