【问题标题】:Python versatile Index slicingPython多功能索引切片
【发布时间】:2019-03-29 22:53:20
【问题描述】:

希望有人可以帮助我将这个 Excel 逻辑转换为 python 的逻辑

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

所以我希望找到一个范围内的所有内容,然后使用该范围内的第一个元素创建一个新列。问题是范围的名称可以更改。

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

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

这个名称可能会改变并且可能包含更少或更多行的问题,并且需要使其更加通用,所以我无法指定编号范围。

这是数据示例:

和 Post 转换我的数据如下所示

【问题讨论】:

  • 您能否解释一下您的解决方案Sales = df.loc['1000 - Cash and Equivalents':'Total - 1000 - Cash and Equivalents'] 是否无法使用,预期的输入是什么?字符串1000 ?或Cash and Equivalents 或其他?
  • 是的,所以我已将 Accounts 列设为 pandas 中的索引并按索引名称切片
  • 是的,它明白,但不确定你想要什么。我的excel知识很差,也没有你的excel数据,所以很难测试和猜测@987654331需要什么@
  • @jezrael 澄清一下,这是我现在正在工作的代码,pastebin.com/51FHMyfj 我希望你能从中看到我的目标
  • 比较好,PL.csv是保密的吗?

标签: python pandas indexing data-modeling data-cleaning


【解决方案1】:

用途:

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'])

【讨论】:

  • 谢谢@Jezrael
猜你喜欢
  • 2015-03-16
  • 2016-10-09
  • 2021-12-31
  • 2021-08-25
  • 2018-10-31
  • 2019-10-28
  • 2021-02-11
  • 1970-01-01
  • 2022-11-03
相关资源
最近更新 更多