如何从 Pandas DataFrame 中的重复行中获取列?

How to get columns from duplicated rows in Pandas DataFrame?

我正在尝试从行中获取数据集中的列。 这是我现在的 DataFrame:

DataFrame

我想要实现的是从索引 0 的列转换以下行:

title:, category:, ..., href:

进入没有重复的列(将有 7 列)并将索引 1 列中的相应行与它们匹配。

Column 1

我试过转置这个数据框,但我不知道如何减少列的数量。

代码:

df = pd.DataFrame(data=items)
df_2 = df.transpose()

输出:

Transposed DataFrame

我也尝试过:

pd.set_index(), pd.groupby(), pd.reset_index()

但是也没用。

非常感谢您的帮助。祝你有美好的一天!

试试这个

df = pd.DataFrame([["title", "hp"],["category", "Laptop"], ["price", 30000], ["title", "lenovo"],["category", "Laptop"], ["price", 40000]],columns=["label", "value"])

print(df)

输出

      label      value
 0    title       hp
 1    category    Laptop
 2    price       30000
 3    title      lenovo
 4    category   Laptop
 5    price      40000

强文本

 label = df["label"].unique()
 a = df.groupby('label')
 df1 = pd.DataFrame()
 for i in label:
     df1[i] = list(a.get_group(i)['value'])

 print(df1)

输出

     title    category  price
 0   hp       Laptop    30000
 1   lenovo   Laptop    40000

不确定你在看什么for.But这可以帮助你