gpt4 book ai didi

python - 将 Pandas Dataframe 的索引拆分为单独的列

转载 作者:行者123 更新时间:2023-12-04 04:19:33 29 4
gpt4 key购买 nike

我有一个使用以下代码从字典创建的 Pandas Dataframe:

import pandas as pd
pd.set_option('max_colwidth', 150)

df = pd.DataFrame.from_dict(data, orient= 'index', columns = ['text'])
df

输出如下:

                                            text
./form/2003Q4/0001041379_2003-12-15.html \n10-K\n1\ng86024e10vk.htm\nAFC ENTERPRISES\n\n\n\nAFC ENTERPRISES\n\n\n\nTable of Contents\n\n\n\n\n\n\n\nUNITED STATES SECURITIES AND EXCHANGE\n...
./form/2007Q2/0001303804_2007-04-17.html \n10-K\n1\na07-6053_210k.htm\nANNUAL REPORT PURSUANT TO SECTION 13 AND 15(D)\n\n\n\n\n\n\n \nUNITED\nSTATES\nSECURITIES AND EXCHANGE\nCOMMISSION...
./form/2007Q2/0001349848_2007-04-02.html \n10-K\n1\nff060310k.txt\n\n UNITED STATES\n SECURITIES AND EXCHANGE COMMISSION\n ...
./form/2014Q1/0001141807_2014-03-31.html \n10-K\n1\nf32414010k.htm\nFOR THE FISCAL YEAR ENDED DECEMBER 31, 2013\n\n\n\nf32414010k.htm\n\n\n\n\n\n\n\n\n\n\nUNITED STATES\nSECURITIES AND EX...
./form/2007Q2/0001341853_2007-04-02.html \n10-K\n1\na07-9697_110k.htm\n10-K\n\n\n\n\n\n\n \n \nUNITED STATES\nSECURITIES AND EXCHANGE COMMISSION\nWashington, D.C. 20549\n \nFORM 10-K\n ...

我需要将第一列(索引)拆分为三个单独的列:Year & Qtr、CIK、Filing Data。因此,这些列中第一行的值将是:2003Q4、0001041379、2003-12-15。

我认为,如果这是在适当的专栏中,我可以使用类似于示例 #2 的代码来执行此操作:

https://www.geeksforgeeks.org/python-pandas-split-strings-into-two-list-columns-using-str-split/

然而,我需要拆分的是索引,而不是命名列,这让我很吃惊。

有没有办法分离索引,或者我是否需要以某种方式将其另存为另一列,这可能吗?

如果有任何帮助,我将不胜感激。我是新手,所以我并不总是理解更困难的解决方案。提前致谢。

最佳答案

列是索引这一事实在从中提取组件时没有区别,但在将这些组件分配回原始数据框时需要小心。

# Extract the components from the index
# pandas allowed us to name the columns via named captured groups
pattern = r'(?P<Quarter>\d{4}Q\d)\/(?P<CIK>\d+)_(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})'
tmp = df.index.str.extract(pattern) \
.assign(Date=lambda x: pd.to_datetime(x[['Year', 'Month', 'Day']]))

# Since `df` and `tmp` are both dataframe, assignments between them
# will be based row label. We want them to align by position (i.e.
# line 1 to line 1) so we have to convert the right hand side to
# numpy array
cols = ['Quarter', 'CIK', 'Date']
df[cols] = tmp[cols].values

关于python - 将 Pandas Dataframe 的索引拆分为单独的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59723565/

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