Python 如何将数据帧中的所有值保存到csv中?
我想使用pandas函数将html转换为csv 这是我在dataframe df中读到的内容的一部分Python 如何将数据帧中的所有值保存到csv中?,python,html,pandas,csv,Python,Html,Pandas,Csv,我想使用pandas函数将html转换为csv 这是我在dataframe df中读到的内容的一部分 0 1 0 sequence 2 1 trainNo K805 2
0 1
0 sequence 2
1 trainNo K805
2 trainNumber K805
3 departStation 鹰潭
4 departStationPy yingtan
5 arriveStation 南昌
6 arriveStationPy nanchang
7 departDate 2020-05-24
8 departTime 03:55
9 arriveDate 2020-05-24
10 arriveTime 05:44
11 isStartStation False
12 isEndStation False
13 runTime 1小时49分钟
14 preSaleTime NaN
15 takeDays 0
16 isBookable True
17 seatList seatNamepriceorderPriceinventoryisBookablebutt...
18 curSeatIndex 0
seatName price orderPrice inventory isBookable buttonDisplayName buttonType
0 硬座 23.5 23.5 99 True NaN 0
1 硬卧 69.5 69.5 99 True NaN 0
2 软卧 104.5 104.5 4 True NaN 0
0 1
0 departDate 2020-05-23
1 departStationList NaN
2 endStationList NaN
3 departStationFilterMap NaN
4 endStationFilterMap NaN
5 departCityName 上海
6 arriveCityName 南昌
7 gtMinPrice NaN
我的代码是这样的
for i, df in enumerate(pd.read_html(html,encoding='utf-8')):
df.to_csv(".\other.csv",index=True,encoding='utf-8-sig')
为了在csv中保留字符,我需要使用utf-8-sig编码。但是我不知道怎么写格式符号%
,0,1
0,departDate,2020-05-23
1,departStationList,
2,endStationList,
3,departStationFilterMap,
4,endStationFilterMap,
5,departCityName,上海
6,arriveCityName,南昌
7,gtMinPrice,
这是我在csv文件中得到的,只保留了最后一部分。
数据帧是正确的,而csv需要更正。您能告诉我如何进行正确的输出吗?- 您正在将每个数据帧保存到同一个文件中,因此每个数据帧都将被覆盖,直到最后一个数据帧
- 请注意,添加了f字符串以更改保存文件名,例如
f“\other{i}.csv”
- 每个数据帧都是不同的形状,因此它们不能正确地组合在一起
(pd.read_html(html,encoding='utf-8'):
df.to_csv(f“\other_{i}.csv”,index=True,encoding='utf-8-sig')
出类拔萃
以pd.ExcelWriter('output.xlsx',mode='w')作为编写器的:
对于i,枚举中的df(pd.read_html(html,encoding='utf-8')):
df.to_excel(writer,sheet_name=f'sheet{i},encoding='utf-8-sig')
@MichaelDelgado正常。我会更新的