【问题标题】:Python - DataFrame returning two columns instead of just onePython - DataFrame 返回两列而不是一列
【发布时间】:2022-12-09 21:51:38
【问题描述】:

为什么我的数据框返回两列?我只想要一栏。我做了几件事,但结果仍然相同。 有一些类似的问题,但我没有找到任何可以帮助我的问题。

for i in Vagas:
    on_click = i.get('onclick')
    temp.append(on_click)


texto = str(temp)

b = {'amp;': '', 'Cadastro': 'https://extranet.ecopatio.com.br/agendamento/Cadastro'}

for x,y in b.items():
    texto = texto.replace(x, y)

achado2 = texto.split('\'')[1::6]


df = pd.DataFrame(achado2)
df.to_csv('testa.csv', mode='a', header=False, index=False)```

【问题讨论】:

  • 告诉我们你得到了什么额外的专栏......没有数据就像没有问题地解决问题

标签: python pandas dataframe selenium web


【解决方案1】:

看起来 df DataFrame 正在返回两列,因为添加到 DataFrame 的数据是一个值列表,它们被添加为单个列。当您在 DataFrame 上调用 to_csv() 方法时,它会将此单列中的值作为两列写入 CSV 文件,每个值都在其自己的列中。

要解决此问题,您可以更改创建 df DataFrame 的行,将值列表添加为 DataFrame 中的单行,而不是单列。为此,您可以将 achado2 列表括在方括号中以创建列表列表,其中每个内部列表包含一个值:

df = pd.DataFrame([achado2])
This will create a DataFrame with a single row and multiple columns, where each column contains a single value from the achado2 list. When you call the to_csv() method on this DataFrame, it will write the values to the CSV file as a single row with multiple columns, as you expect.

或者,您可以使用 pd.Series() 构造函数从 achado2 列表创建 Pandas Series,然后将 Series 传递给 pd.DataFrame() 构造函数以创建具有单列和多行的 DataFrame:

achado2_series = pd.Series(achado2)
df = pd.DataFrame(achado2_series)

这将创建一个具有单列和多行的 DataFrame,其中每行包含来自 achado2 列表的单个值。当您在此 DataFrame 上调用 to_csv() 方法时,它会将值作为包含多行的单列写入 CSV 文件。

在任何一种情况下,生成的 DataFrame 都应该具有所需的结构,其中一个列包含 achado2 列表中的值。

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多