Python 用另一个数据帧快速创建数据帧

Python 用另一个数据帧快速创建数据帧,python,pandas,Python,Pandas,我有一个数据框,看起来像这样: index | in | out | time 7 | 8 | 8 | 232 11 | 3 | 0 | 0 79 | 0 | 8 | 12 我想在此基础上创建一个数据帧,其中每个非零的输入/输出值都被设置为1(它们都是正数)时间和索引应相同: index | in | out | time 7 | 1 | 1 | 232 11 | 1 | 0 | 0 79 | 0 |

我有一个数据框,看起来像这样:

index | in | out | time
   7  |  8 |  8  |  232
  11  |  3 |  0  |    0
  79  |  0 |  8  |   12
我想在此基础上创建一个数据帧,其中每个非零的输入/输出值都被设置为1(它们都是正数)<代码>时间和
索引
应相同:

index | in | out | time
   7  |  1 |  1  |  232
  11  |  1 |  0  |    0
  79  |  0 |  1  |   12
我认为应该有一个比我现在做的更快的方法:

df2 = pd.DataFrame({"index":[], "in":[], "out":[], "time":[]})
for index, row in df.iterrows():
    if row["in"] == 0:
        in_val = 0
    else:
        in_val = 1
    if row["out"] == 0: 
        out_val = 0
    else:
        out_val = 1
    time = row["time"]
    df2 = df2.append(pd.DataFrame({"index":[index], "in":[in_val], "out":[out_val], "time":[time]}), sort=False)
我可以使用一些lambda函数或类似列表理解的东西来更快地转换数据帧吗

与包含列表的列一起使用:

cols = ['in','out']
df[cols] = np.where(df[cols].eq(0), 0, 1)
不等于整数的或强制转换布尔掩码:

df[cols] = df[cols].ne(0).astype(int)
如果没有负值,则使用:

使用

或者,您可以使用转换为布尔值并与1相乘:

cols=['in','out']
df[cols]=df[cols].astype(bool)*1


所以你有一个这样的数据帧

    index   in  out     time
0   7   8   8   232
1   11  3   0   0
2   79  0   8   12
df['in'] = np.where(df['in'] > 0, 1, 0)
df['out' = np.where(df['out'] > 0, 1, 0)
使用
np.where
获得如下所需的结果

    index   in  out     time
0   7   8   8   232
1   11  3   0   0
2   79  0   8   12
df['in'] = np.where(df['in'] > 0, 1, 0)
df['out' = np.where(df['out'] > 0, 1, 0)
你可以试试

df['in']=[1如果i>0,则列表中的i为0(df['in'])]

使用
np.where
将除1以外的值更改为1
    index   in  out     time
0   7   8   8   232
1   11  3   0   0
2   79  0   8   12
df['in'] = np.where(df['in'] > 0, 1, 0)
df['out' = np.where(df['out'] > 0, 1, 0)