python - 比较pandas Df中的每一行值元素并根据比较输入一个字符串

标签 python python-3.x pandas dataframe warnings

我是处理 Pandas Df 的新手。 我想比较每一行的每一列元素。

要求: 如果 1 行的列中的所有元素都为零,则在新列中输入“More False”,该列用对应于其索引的零填充。

看下面的Df可以清楚的理解

My Data Frame:

       Time     Brake      Speed         Strgangle   index   Target
0     1678.39  0.000000   0.000000        0.000000  167739      0
1     1678.40  15.00000   0.000000        0.000000  167740      0
2     1678.41  0.000000   8.000000        0.000000  167741      0
3     1678.42  0.000000   0.000000        2.000000  167742      0
4     1678.43  5.000000   20.10000        0.000000  167743      0
5     1678.44  0.150000   0.000000        -1.16500  167744      0
6     1678.45  0.000000   20.10           2.000000  167742      0
7     1678.47  0.150000   25.00000        -1.16500  167744      0


My Requirement :

1. If Brake = 0, Speed =0, Strg angle=0 
--> Input a str in corresponding Target index as 'More False'
2. If Brake = Value, Speed = Value, Strg angle=Value 
--> Input a str in corresponding Target index as 'More True'
3. As above conditions i should input the string in Target column based on my requirement

.

需要的实际 Df :

       Time     Brake      Speed         Strgangle   index   Target
0     1678.39  0.000000   0.000000        0.000000  167739      MoreFalse
1     1678.40  15.00000   0.000000        0.000000  167740      False
2     1678.41  0.000000   8.000000        0.000000  167741      False
3     1678.42  0.000000   0.000000        2.000000  167742      False
4     1678.43  5.000000   20.10000        0.000000  167743      True
5     1678.44  0.150000   0.000000        -1.16500  167744      True
6     1678.45  0.000000   20.10           2.000000  167742      True
7     1678.47  0.150000   25.00000        -1.16500  167744      MoreTrue

我尝试使用 If 循环在目标列中输入我需要的字符串,但我收到 SettingWithcopy 警告。

我相信对于上述问题会有一些简单的方法。

最佳答案

因为你只有 4 种可能性,所以找出列中非零值的数量,然后映射结果:

d = {0: 'MoreFalse', 1: 'False', 2: 'True', 3: 'MoreTrue'}
df['Target'] = df[['Brake', 'Speed', 'Strgangle']].ne(0).sum(1).map(d)

输出:

      Time  Brake  Speed  Strgangle   index     Target
0  1678.39   0.00    0.0      0.000  167739  MoreFalse
1  1678.40  15.00    0.0      0.000  167740      False
2  1678.41   0.00    8.0      0.000  167741      False
3  1678.42   0.00    0.0      2.000  167742      False
4  1678.43   5.00   20.1      0.000  167743       True
5  1678.44   0.15    0.0     -1.165  167744       True
6  1678.45   0.00   20.1      2.000  167742       True
7  1678.47   0.15   25.0     -1.165  167744   MoreTrue

关于python - 比较pandas Df中的每一行值元素并根据比较输入一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54331172/

相关文章:

python - 在 python 中编写一个文本文件中的列表

python - 扫雷游戏的网格生成

python - 如何拆分 Pandas 中的几列数据?

python - 属性错误: 'Series' object has no attribute 'columns'

python - 使用 Pandas 选定列的 CSV 到 JSON

python - 根据用户输入创建对象

python - Pip freeze 给我这个与 git 相关的错误

python - 使用 .loc 查询非空值和仅字符串值

python - 遍历嵌套字典

python - 重新排序数据框的列索引