gpt4 book ai didi

python - 如何将函数应用于 pandas 数据框中列中的每个值?

转载 作者:行者123 更新时间:2023-12-01 03:48:28 26 4
gpt4 key购买 nike

我曾尝试使用如下循环进行某种手动方法:

data = pd.read_csv('data/training.csv')
for idx,imageString in enumerate(data.iloc[:,-1]):
# print(imageString[0:10])
data[idx,-1] = imageString.split(" ")

但是最后一行出现错误:

ValueError: Length of values does not match length of index

所以我的问题是:

  1. 谁能解释一下为什么我会收到上述错误以及我该怎么办绕过它?
  2. 这是将分割应用于每个的正确方法吗?我的数据框最后一列的值?

关于 #2 - 我看到有些人使用 applymap 但我认为这会创建一个新列,我真的只想用另一个列表替换现有列中的值。

最佳答案

我认为你需要str.split :

data = pd.read_csv('data/training.csv')
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False)

然后使用 str[1]str[n] 选择列表中的第一个或其他一些元素:

data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[0]
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[n]

示例:

import pandas as pd

data = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':['aa aa','ss uu','ee tt']})

print (data)
A B C D E F
0 1 4 7 1 5 aa aa
1 2 5 8 3 3 ss uu
2 3 6 9 5 6 ee tt

print (data.iloc[:,-1].str.split(expand=False))
0 [aa, aa]
1 [ss, uu]
2 [ee, tt]
Name: F, dtype: object

data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[0]
print (data)
A B C D E F
0 1 4 7 1 5 aa
1 2 5 8 3 3 ss
2 3 6 9 5 6 ee
<小时/>
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False).str[1]
print (data)
A B C D E F
0 1 4 7 1 5 aa
1 2 5 8 3 3 uu
2 3 6 9 5 6 tt

Can anyone explain why I am getting the above error and how can I get around it?

问题是imageString.split("")返回list并且如果分配给data[idx,-1],元素的长度字符串的长度小于所有 DataFrame 的长度。

Is this the proper way to apply a split to every value in the last column of my data frame?

更好的是使用字符串方法,请参阅 pandas documentation .

关于python - 如何将函数应用于 pandas 数据框中列中的每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38559967/

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