Python多功能索引切片

2024-04-25 06:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人能帮我把Excel逻辑转换成python

=IF(LEFT(A8,5)="Total",A9,I8)

因此,我希望找到一个范围内的所有内容,然后创建一个包含该范围内第一个元素的新列。问题是范围的名称可能会更改。你知道吗

我实现的当前解决方案是将列转换为索引,并通过执行以下操作手动选择“按索引名”:

Sales = df.loc['1000 - Cash and Equivalents':'Total - 1000 - Cash and Equivalents']

这个名字的问题可能会改变,可能包含更少或更多的行,并且需要使这个更通用,所以我不能指定一个编号的范围。你知道吗

这是一个数据示例:

enter image description here

变换后的数据如下:

enter image description here


Tags: and数据名称元素内容ifcash逻辑
1条回答
网友
1楼 · 发布于 2024-04-25 06:30:10

用途:

df = pd.read_csv('PL2.csv', encoding='cp1252', engine='python')


#create helper df for total strings
df1 = df.loc[df.iloc[:, 0].str.startswith('Total', na=False), df.columns[0]].to_frame('total')
#first column without Total - 
df1['first'] = df1['total'].str.replace('Total - ', '')
print (df1.head(10))
                                    total                          first
17                   Total - 4000 - Sales                   4000 - Sales
21  Total - 4200 - Discounts & Allowances  4200 - Discounts & Allowances
24       Total - 4400 - Excise and Duties       4400 - Excise and Duties
25                          Total - Sales                          Sales
37      Total - 5000 - Cost of Goods Sold      5000 - Cost of Goods Sold

#create index by first column
df = df.set_index(df.columns[0])

#filter function - if not matched return empty df
def get_dict(df, first, last):
    try:
        df = df.loc[first: last]
        df['Sub-Category'] = first
    except KeyError:
        df = pd.DataFrame()
    return df

#in dictionary comprehension create dict of DataFrames     
d = {k: get_dict(df, k, v) for k, v in zip(df1['first'], df1['total'])}
#print (d)

#select Sales df
print (d['Sales'])

相关问题 更多 >