Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python子字符串dataframe列工作不正常_Python 3.x_Pandas - Fatal编程技术网

Python 3.x Python子字符串dataframe列工作不正常

Python 3.x Python子字符串dataframe列工作不正常,python-3.x,pandas,Python 3.x,Pandas,我使用的代码如下所示 output_df['test'] = str(output_df['givencolumn'].str[0:2]) 我无法理解为什么.str[0:2]会在输出的测试列中返回如下内容 虽然看起来很简单,但我无法找出错误发生的地方。请帮助我解决这个问题,而不是样本文件 我希望我的测试专栏看起来像这样 Index test 0 01 1 01 2 01 3 01 4 01 所以,我现在发现了问题:- 这是有效的 outpu

我使用的代码如下所示

output_df['test'] = str(output_df['givencolumn'].str[0:2])
我无法理解为什么.str[0:2]会在输出的测试列中返回如下内容

虽然看起来很简单,但我无法找出错误发生的地方。请帮助我解决这个问题,而不是样本文件

我希望我的测试专栏看起来像这样

Index  test
0      01
1      01
2      01
3      01
4      01
所以,我现在发现了问题:-

这是有效的

output_df['test'] = output_df['givencolumn'].str[0:2]
这不起作用:-

starting_position = 0
ending_position = 2

given_data[required_column_name] = given_data['givencolumn'].str[starting_position:ending_position]
我的职能:-

def build_columns(given_data,given_layout):
    for i in range(0, 2):
        required_column_name = str(given_layout.iloc[i][1])
        starting_position = int(given_layout.iloc[i][2])
        ending_position = int(given_layout.iloc[i][4])
        print(starting_position)
        print(ending_position)
        given_data[required_column_name] = str(output_df['givencolumn'])        
        given_data[required_column_name] = given_data['givencolumn'].str[1:2]
    return(given_data)

你不需要str电话。它的工作原理如下:

df= pd.DataFrame({'test': [
        '00',
        '012'
        '013',
        '02'
]})

df['test2']= df['test'].str[:2]
df
不确定,为什么要用列调用str。我想这可能是问题所在,因为.str[:2]生成的不是字符串,而是由字符串组成的序列,如果要指定一个值,而该值取决于其他行值或该行的索引,则应该指定该值。也许这是一种误解。如果您执行类似pd.DataFrame['col']=scalarValue的操作,它会将值分配给所有行中的字段。但一般来说,你会分配序列。例如,如果您有一个数字列,比如说今年的工资,您希望分配下一年的工资,包括5%的加薪,那么您的代码可能如下所示

salrary_df['salary_2020']= salrary_df['salary_2019'] * 1.05

可以看出,pandas实际上是为每一行执行这个赋值,但不是这样做的。事实上,它执行右侧,生成一个序列,然后在内部将序列分配给列。它可能会将其复制到共享相同数据类型的多个列的数组中,以提高处理效率。

什么是printoutput_df['givencolumn'].str[0:2]托利斯特先生?你能告诉我你到底在做什么吗expect@jezrael.tolist正在返回一个['01',01',01'..]hmm的列表,如果使用output_df['test']=output_df['givencolumn'].str[0:2]同样的问题?如果选中printoutput_df['givencolumn'].tolist只有字符串?@jezrael用该问题更新了问题。对于您来说,df['test2']=strdf['test'].str[:2]不起作用?对我来说很好。更新了问题中的问题。它不会产生运行时错误,但我猜这不是海报的意图,因为它使用str方法将序列转换为字符串,并将相同的值分配给所有行。对吗?顺便说一句,你真的确定给定的数据[必需的列名称]=给定的数据['givencolumn']。str[起始位置:结束位置]没有给出相同的结果吗?如果是这样的话,那么在pandas中就不会有问题,但是python解释器会有问题,因为传递给[]的是解析器/解释器预处理的结果,与pandas无关。