python - 如何将一片数据帧转换为新的数据帧

标签 python pandas dataframe slice

我是 python 的新手,有时对某些操作感到困惑 我有一个名为 ro 的数据框,我还使用特定列 PN 3D 过滤了此数据框以获得特定值 921 并分配了结果使用以下代码将其放入名为 headlamp 的新数据框中:

 headlamp = ro[ro['PN 3D']=="921"]

我的头灯也是一个dataframe还是只是一个slice? 我问这个问题的原因是我稍后在我的脚本中收到一些奇怪的警告和结果。

例如,我创建了一个名为 word 的新列,并将其分配给 headlamp

 headlamp['word'] = ""

我收到以下警告:

 A value is trying to be set on a copy of a slice from a DataFrame

之后,我使用以下脚本将结果分配给 headlamp['word']

 i = 0
 for row in headlamp['Comment'].astype(list):
     headlamp['word'][i] = Counter(str(row).split())
 i+=1
 print headlamp['word']

同样的警告出现了,它影响了我的结果,因为当我使用 headlamp.tail() 时,headlamp['word'] 的最后一行是空的。

有没有人知道问题是什么以及如何解决?

任何帮助将不胜感激

最佳答案

使用.loc

headlamp = ro.loc[ro['PN 3D']=="921"]

至于剩下的和你的评论……我很困惑。但这是我最好的猜测

设置

import pandas as pd
from string import ascii_lowercase

chars = ascii_lowercase + ' '
probs = [0.03] * 26 + [.22]

headlamp = pd.DataFrame(np.random.choice(list(chars), (10, 100), p=probs)).sum(1).to_frame('comment')
headlamp

enter image description here

headlamp['word'] = headlamp.comment.str.split().apply(lambda x: pd.value_counts(x).to_dict())
headlamp

enter image description here

关于python - 如何将一片数据帧转换为新的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075924/

相关文章:

python - 如何导入一列为时间格式 hh :mm:ss and plot it in x axis with pandas? 的 csv 文件

python - 使用 dataframe.loc 时无法将 dtyped [datetime64[ns]] 数组与 [bool] 类型的标量进行比较的错误

r - 比较两列并更改第三列时如何使用 ifelse?

python - igraph python 摘要未按预期工作

python - 用 C 扩展 python,返回 numpy 数组给出垃圾

python - 如何有效地填充由列表中值的成对组合组成的不完整 pandas 数据框?

python - 如何从 Pandas 中的 m8[ns] 对象中获取小时数?

python - 如何将程序的输出重定向到数据框

python - 使用 Python 从 gradle 文件中提取依赖项和版本

python - 使 python __doc__ 属性在 Windows CMD 窗口中正确显示?