gpt4 book ai didi

python - 当从具有多索引列的 DataFrame 中提取系列时,我无法使用 read_csv 读取

转载 作者:太空宇宙 更新时间:2023-11-03 17:06:15 24 4
gpt4 key购买 nike

我有以下数据框:

>>>df
A B
c1 c2 c1 c2
1.1.2000 10 11 10 9
2.1.2000 11 9 7 10
.....

现在我想将每一列单独保存到 CSV 文件中。 (别问为什么。我只是必须这么做。)

for column_name, series in df.iteritems():
series.to_csv(filename, sep=";", header=True, date_format="%d.%m.%Y", decimal=',')

注意:

series.name ['A', 'c1'] etc. Always a list of strings instead of a string.

到目前为止一切顺利。然后我想再读一遍这个系列:

series = pd.read_csv(filename, index_col=0, sep=";", squeeze=True, decimal=',', parse_dates=True, dayfirst=True)

但我得到:

>>>series
NaT c1
NaT NaN
2010-01-01 10
2010-01-02 11
.....
Name: A

标题都混淆了。我怀疑这是因为多重索引。如何安全地向/从具有多索引列的 cvs 文件写入和读取?

最佳答案

您可以使用header=[0, 1]命令:

iterables = [['bar', 'baz', 'foo'], ['one', 'two']]
arrays = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
index = pd.date_range(datetime(2015,1,1), periods=4)
df = pd.DataFrame(np.random.randn(4, 6), columns=arrays, index=index)

first bar baz foo
second one two one two one two
2015-01-01 0.668995 -2.938213 -0.829942 -0.450692 0.512050 -0.845328
2015-01-02 2.056507 -0.393159 0.682482 -1.298044 0.326979 0.281078
2015-01-03 0.651219 -1.455091 0.469010 0.309703 2.518411 0.054144
2015-01-04 0.905059 0.282328 -1.315723 0.306234 -1.640091 -1.962590

df.to_csv('multi.csv')
test = pd.read_csv('multi.csv', header=[0,1])

first bar baz foo
second one two one two one two
0 2015-01-01 0.668995 -2.938213 -0.829942 -0.450692 0.512050 -0.845328
1 2015-01-02 2.056507 -0.393159 0.682482 -1.298044 0.326979 0.281078
2 2015-01-03 0.651219 -1.455091 0.469010 0.309703 2.518411 0.054144
3 2015-01-04 0.905059 0.282328 -1.315723 0.306234 -1.640091 -1.962590

关于python - 当从具有多索引列的 DataFrame 中提取系列时,我无法使用 read_csv 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com