python - How to merger same column values based on other column values?
问题描述
How to add a new column in pandas dataframe based on other column values , for example, Id columns has value and column Value has different values for Id, it needs to be merged as in the output.
df:
# dictionary of lists
data = {'Id':["A", "A", "B", "B","B", "C", "D","E","E", "F", "G","G"],
'Value': ["10$", "2$", "30%", "43%", "12$", "43$", "27$", "40%" ,
"18$",np.nan,np.nan,"89%"]}
df = pd.DataFrame(data)
print(df)
Id Value
0 A 10$
1 A 2$
2 B 30%
3 B 43%
4 B 12$
5 C 43$
6 D 27$
7 E 40%
8 E 18$
9 F nan
10 G nan
11 G 89%
output :
Id Value
0 A 10$, 2$
1 B 30%,43%,12$
3 C 43$
4 D 27$
5 E 40%,18$
6 F nan
7 G 89%
解决方案
df.groupby('Id')['Value'].apply(', '.join).reset_index()
print(df)
Output:
Id Value
0 A S1, S2
1 B S3, S3, S5
2 C S6
3 D S7
4 E S8, S9
推荐阅读
- scala - 在 Spark 2.3 中将元素添加到结构数组并合并结构数组
- javascript - 这段代码是如何工作的,我没有清楚地理解?
- php - 如何检查给定键值对的多维数组,即。完全相同的键和值?
- java - 在 Android Studio 3.5.1 中这是什么类型的问题?
- php - 文件上传在 AWS Linux 2 服务器中不能超过 10mb?
- c# - 使用 JsonSerializer.DeserializeAsync 反序列化 JSON 不使用我的 JsonConverter
- android - 无法在android中进行无线调试(ADB)
- python - tflite.allocate_tensors() 在更改输入大小后失败
- swift - Braintree,跳过显示 Dropin 并直接选择 PayPal
- javascript - 第一个兄弟 div 被视为第二个动态 div 的背景