pandas 如何使用字符串在panda中设置iloc

9njqaruj  于 2023-02-20  发布在  其他
关注(0)|答案(3)|浏览(122)

我对国际劳工组织的一般用法理解如下。

import pandas as pd
df = pd.DataFrame([[1,2,3,4,5],[4,5,6,4,5],[7,8,9,4,5],[10,11,12,4,5]])
df_ = df.iloc[:, 1:4]

另一方面,尽管使用是有限的,但是否可以使用字符串设置iloc?
下面是伪代码,不能正常工作,但我想这样做。

import pandas as pd
df = pd.DataFrame([[1,2,3,4,5],[4,5,6,4,5],[7,8,9,4,5],[10,11,12,4,5]])
df.columns = ["money","job","fruits","animals","height"]
tests = ["1:2","2:3", "1:4"]
for i in tests:
    print(df.iloc[:,i])

有没有更好的方法使用函数将字符串拆分为“start_col”和“end_col”?

fnx2tebb

fnx2tebb1#

您只需创建一个转换器函数:

import pandas as pd
df = pd.DataFrame([[1,2,3,4,5],[4,5,6,4,5],[7,8,9,4,5],[10,11,12,4,5]])
ranges = ["1:2", "2:3", "1:4"]

def as_int_range(ranges):
    return [i for rng in ranges for i in range(*map(int, rng.split(':')))]

df.iloc[as_int_range(ranges),:]

    0   1   2  3  4
1   4   5   6  4  5
2   7   8   9  4  5
1   4   5   6  4  5
2   7   8   9  4  5
3  10  11  12  4  5
dz6r00yl

dz6r00yl2#

iloc[ ]用于对数值数据进行切片。对于String切片,可以像对数字使用iloc[ ]一样使用loc[ ]。以下是实现loc[ ]https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html的官方panda文档

j8yoct9x

j8yoct9x3#

我在最初的问题中没有提到它,我写了一个支持[“1:3,4”]这样的例子的程序。

import pandas as pd

df = pd.DataFrame([[1,2,3,4,5],[4,5,6,4,5],[7,8,9,4,5],[10,11,12,4,5]])
df.columns = ["a", "b", "c" , "d", "e"]

def args_to_list(string):
    strings = string.split(",")
    column_list = []
    for each_string in strings:
        each_string = each_string.strip()
        if ":" in each_string:
            start_ , end_  = each_string.split(":")
            for i in range(int(start_), int(end_)):
                column_list.append(i)
        else:
            column_list.append(int(each_string))

    return column_list
    
tests = ["1:2", "1,2,3,4", "1:2,3", "1,2:3,4"]

for i in tests:
    list_ =args_to_list(i)
    print(list_)
    print(df.iloc[:, list_])
    print(list_)

相关问题