Pandas 数据帧行转为 CSV 行无法正常工作

huangapple go评论113阅读模式
英文:

Pandas dataframe row to csv row doesn't work

问题

我正在使用这个网站上的代码(https://stackoverflow.com/questions/40413741/pandas-csv-output-only-the-data-in-a-certain-row-to-csv)来将一个数据框的行写入一个CSV行:

    df.iloc[-1].to_csv('output.csv', mode='a', index=False, header=False)

但结果是

    1
    2
    3
    4
    5

而不是

`1, 2, 3, 4, 5`

这里有什么问题?

我想让这个与`df.to_csv`一起工作,我尝试了一些选项。我知道我可以使用不同的代码,比如`with open(...)`,但`open()`函数会与另一个我无法更改的列表变量冲突。
英文:

I was using code from this site (https://stackoverflow.com/questions/40413741/pandas-csv-output-only-the-data-in-a-certain-row-to-csv)
to write a dataframe row to a csv row:

df.iloc[-1].to_csv('output.csv', mode='a', index=False, header=False)

but the result is

1
2
3
4
5

instead of

1, 2, 3, 4, 5

What is wrong here?

I want to make this work with df.to_csv and I've tried a few options. I know I could use different code such as with open(...) but the open() function conflicts with another list variable that I cannot change.

答案1

得分: 0

在你的解决方案中,你得到了一个pd.Series,所以你无法得到期望的结果。但是下面的解决方案将返回一个pd.DataFrame的行,所以我认为你可以得到你想要的。

df.iloc[-1:].to_csv('output.csv', mode='a', index=False, header=False)
英文:

in your solution, you are getting pd.Series so you cant get the desired result. But the below solution will return you a pd.DataFrame row, so i think you can get what you want.

df.iloc[-1:].to_csv('output.csv', mode='a', index=False, header=False)

答案2

得分: 0

`df.iloc[-1]` 给出一个 `pd.Series`,其单独的值类似于 `pd.DataFrame` 中的单列行这就是它被导出到输出 csv 中的方式每个值占一行)。<br>要获得预期的结果您需要将您的 `Series` 转换为只有一条记录/行的 `DataFrame`,可以通过两种方式实现

- "长" 方法:`pd.DataFrame(columns=df.iloc[-1].index, data=[df.iloc[-1]]).to_csv('output.csv', mode='a', header=False, index=False)`

- 简短方式:`df.iloc[-1].to_frame().T.to_csv('output.csv', mode='a', header=False, index=False)`
英文:

df.iloc[-1] gives you a pd.Series whose separate value is analogues to pd.DataFrame row with a single column, and that's how it's exported into your output csv (each value on a separate line).<br>To get the expected result you need to transform your Series into a DataFrame with one record/row and that's could be achieved in 2 ways:

  • "long" way: pd.DataFrame(columns=df.iloc[-1].index, data=[df.iloc[-1]]).to_csv(&#39;output.csv&#39;, mode=&#39;a&#39;, header=False, index=False)

  • short way: df.iloc[-1].to_frame().T.to_csv(&#39;output.csv&#39;, mode=&#39;a&#39;, header=False, index=False)

huangapple
  • 本文由 发表于 2023年2月24日 02:30:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定