簡體   English   中英

如何在 Python 中將數據框形狀從多行更改為單行?

[英]How to change the dataframe shape from multiple rows to a single row in Python?

我有這個數據農場;

df = pd.DataFrame({'image_id':'490.png', 'labels':['logo_sony', 'text', 'text', 'object_headphone', 'text', 'button']})

它返回一個 6 行 2 列的數據框。

   image_id   labels
0   490.png  logo_sony
1   490.png  text
2   490.png  text
3   490.png  object_headphone
4   490.png  text
5   490.png  button

我怎樣才能使它有兩列的一行,如下所示

    image_id          labels
0   490.png         'logo_sony', 'text', 'text', 'object_headphone', 'text', 'button'

謝謝

一個簡單的解決方案是使用字符串而不是列表作為標簽值:

labels = "'logo_sony', 'text', 'text', 'object_headphone', 'text', 'button'"
df = pd.DataFrame({'image_id':['490.png'], 'labels':labels})
print(df)

輸出

  image_id                                             labels
0  490.png  'logo_sony', 'text', 'text', 'object_headphone...

您可以將輸入dict中的list轉換為空格分隔的str並在 -

df = pd.DataFrame({k: [' '.join(v)] if isinstance(v, list) else [v] for k, v in d.items()})

輸出

  image_id                                            labels
0  490.png  logo_sony text text object_headphone text button

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM