【问题标题】:How can I convert array to dataframe?如何将数组转换为数据框?
【发布时间】:2021-08-21 06:23:43
【问题描述】:

我有一个数据框:

ID
239200202
14700993
1153709258720067584

并以数组形式 [1,1,0] 输出 id 是否为机器人 如何将其组合成一个数据框,例如:

ID Bot
239200202 bot
14700993 bot
1153709258720067584 Not bot

我试过这段代码,但没有用:

test = pd.read_csv('./user_data/user_lookup/dataset/test_dataframe.csv', index_col=1)
df = pd.DataFrame(columns=['UserID','Bot/Not'])
for index,row in test.iterrows():
   if test[index] == 1:
      df.loc[index,['UserID']] = test['User ID']
      df.loc[index,['Bot/Not']] = 'Bot'
   if test[index] == 0:
      df.loc[index, ['UserID']] = test['User ID']
      df.loc[index, ['Bot/Not']] = 'Not-Bot'
print(df)

如果有人可以帮助我,那就太好了。 谢谢

【问题讨论】:

  • test_dataframe.csv 是否仅包含 ID?
  • 数组的名称是什么?
  • 是的 test_dataframe.csv 只有 ids。我删除了其余的列,因为我不需要它。
  • array 是一个输出:pred_logreg_test = logreg.predict(test_scaled) 我正在预测输出数组的 id 是否是机器人
  • 你可以使用pandas assign,对于你的数组/列表你可以做一个列表理解arr =[1,1,0]arr = ['Bot' if x==1 else 'Not-Bot' for x in arr]

标签: python python-3.x pandas dataframe csv


【解决方案1】:

根据你在问题中给出的提示,

您可以将列名Bot 添加到测试数据框中,如下所示:

new_pred = ['bot' if x==1 else 'Not bot' for x in pred_logreg_test]
test['Bot'] = list(new_pred)

【讨论】:

    【解决方案2】:

    以上问题的解决方法如下

    array = [1,1,0]
    df['BOT']=df.loc[df['ID'].isin(array)]
    

    【讨论】:

      【解决方案3】:

      这里最好与 pd.concat 一起使用,将这 2 个 df 合并为一个

      另外,在使用 DataFrames 时尽量避免迭代,它的速度要慢得多

      示例:

      import pandas as pd
      import numpy as np
      
      df = pd.DataFrame({'ID': [100, 101, 102]})
      bot_not_bot = np.array([1,0,1])
      df = pd.concat([df, pd.DataFrame({'bot/not bot': bot_not_bot})], axis=1)
      

      不要使用速度较慢的 iterrows,而是使用 apply 在较大规模的 DataFrames 上获得更快的结果

      df['bot/not bot'] = df['bot/not bot'].apply(lambda x: 'Bot' if x else 'Not Bot')
      

      这是使用Dataframes的正确方法,避免迭代

      【讨论】:

        【解决方案4】:

        对数组使用索引:

        df = pd.DataFrame({'UserID': [239200202, 14700993, 1153709258720067584]})
        is_bot = np.array([1,1,0])
        df['Bot'] = np.array(['not bot', 'bot'])[is_bot]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-11
          • 1970-01-01
          • 2020-09-21
          • 2022-11-04
          • 2021-02-10
          • 2014-03-23
          相关资源
          最近更新 更多