如何与相同值合并DF的行

发布于 2025-02-13 15:56:46 字数 1022 浏览 1 评论 0原文

我正在使用python上的熊猫面临问题,但我无法解决。 我想合并/组合/重组具有相同URL的行。

编辑 : 我有一个像这样的数据框架:

urlcol1col2col3col4
aaAxxyy
bbbzz
aaaee
aa

我想要这样的东西:

urlcol1 col1col2col2 col3col3 col4
aaa aaaaaa aaa eexxyy
bbbzz cccc cc
cc aa

我尝试过使用Groupby,但是在我的df有没有URL的数据,我想保留它们。 我还尝试过与内部合并,这给了我不错的结果,但是我不知道为什么它会破坏DF内部的行数。

谢谢。

I am facing a problem using pandas on python and i can't solve it.
I would like to merge/combine/regroup the rows which have the same url.

EDIT :
I have a dataframe looking like this :

urlcol1col2col3col4
aaaxxyy
bbbzz
aaaee
AA

I would like something like this :

urlcol1col2col3col4
aaaeexxyy
bbbzzcc
AA

I've tried using groupby, but in my df i've datas which don't have URL and i want to keep them.
I've also tried merge with inner, which gives me pretty good results but i don't know why it decuplates the number of rows inside my df.

thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

极度宠爱 2025-02-20 15:56:47

您可以使用groupbyfirst

df = df.groupby('url', as_index=False).first()

You can use groupby and first.

df = df.groupby('url', as_index=False).first()
暖阳 2025-02-20 15:56:47

我认为您应该使用Groupby,Nunique和NP.Where来解决此问题。
请参阅以下有关此问题的讨论。
pandas-dataframe-check-check-check-frame-check-if-multiple-multiple-multiple-lows-有个性值

I think you should use groupby, nunique, and np.where to solve this issue.
See the following discussion regarding this problem.
pandas-dataframe-check-if-multiple-rows-have-the-same-value

爱你是孤单的心事 2025-02-20 15:56:47
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'url': ['url1', 'url2'], 'col1':['A', np.nan], 'col2':[np.nan, 'B']}).set_index('url')
df2 = pd.DataFrame({'url': ['url1', 'url2'], 'col1':[np.nan, 'C'], 'col2':['D', np.nan]}).set_index('url')
df1.fillna(df2, inplace=True)
print(df1)

结果:

     col1 col2
url           
url1    A    D
url2    C    B
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'url': ['url1', 'url2'], 'col1':['A', np.nan], 'col2':[np.nan, 'B']}).set_index('url')
df2 = pd.DataFrame({'url': ['url1', 'url2'], 'col1':[np.nan, 'C'], 'col2':['D', np.nan]}).set_index('url')
df1.fillna(df2, inplace=True)
print(df1)

Result:

     col1 col2
url           
url1    A    D
url2    C    B
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文