![](/img/trans.png)
[英]Merge multiple column values into one column as list in python pandas
[英]Pandas Merge row data with multiple values to Python list for a column
我有一個看起來像的數據框
*id*, *name*, *URL*, *Type*
2, birth_france_by_region, http://abc. com, T1
2, birth_france_by_region, http://pt. python, T2
3, long_lat, http://abc. com, T3
3, long_lat, http://pqur. com, T1
4, random_time_series, http://sadsdc. com, T2
4, random_time_series, http://sadcadf. com, T3
5, birth_names, http://google. com, T1
5, birth_names, http://helloworld. com,T2
5, birth_names, http://hu. com, T3
我想要一個此數據幀合並id相等的行,並有一個Type列表對應於URL列表,所以最終輸出應類似於
*id*, *name*, *URL*, *Type*
2,birth_france_by_region, [http://abc .com,http://pt.python], [T1,T2]
3,long_lat, [http://abc .com,http://pqur. com], [T3,T1]
4,random_time_series, [http://sadsdc. com,http://sadcadf .com,],[T2,T3]
5,birth_names, [http://google .com,http://helloworld. com,
http://hu. com] , [T1,T2,T3]
我認為您需要groupby
和聚合tuple
,然后轉換為list
:
df = df.groupby(['id','name']).agg(lambda x: tuple(x)).applymap(list).reset_index()
print (df)
id name \
0 2 birth_france_by_region
1 3 long_lat
2 4 random_time_series
3 5 birth_names
URL Type
0 [http://abc.cm, http://pt.python] [T1, T2]
1 [http://abc.cm, http://pqur.com] [T3, T1]
2 [http://sadsdc.com, http://sadcadf.com] [T2, T3]
3 [http://google.;com, http://helloworld.com, ht... [T1, T2, T3]
因為在0.20.3版本中引發錯誤:
df = df.groupby(['id','name']).agg(lambda x: x.tolist())
ValueError:函數不會減少
這將為您提供“ URL”列的預期結果:
test.groupby(["id", "name"])['URL'].apply(list)
id name
2 birth_france_by_region [http://abc. com, http://pt. python]
3 long_lat [http://abc. com, http://pqur. com]
4 random_time_series [http://sadsdc. com, http://sadcadf. com]
5 birth_names [http://google. com, http://helloworld. com, h...
但是,我找不到URL和Type列的解決方案。
我可以建議分兩個步驟進行:
temp_table1 = test.groupby(["id", "name"])['URL'].apply(list)
temp_table2 = test.groupby(["id", "name"])['Type'].apply(list)
temp_table1
和temp_table2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.