【问题标题】:How to get CSV odd and even lines in Python?如何在 Python 中获取 CSV 奇偶行?
【发布时间】:2021-11-23 03:44:07
【问题描述】:

我正在将 R 脚本转换为 Python。

我的实际 Python 代码:

table_NameUrl = pd.read_csv("Data.txt", sep=";", header= None)
table_Size = len(table_NameUrl)
sequence = np.arange(1, table_Size, 2)
for i in sequence:
    print("Table name: " + str(table_NameUrl[[1]][i]))
    print("URL: " + str(table_NameUrl[[1]][i + 1]))
    tableName = table_NameUrl[[1]][i]
    tableUrl = table_NameUrl[[1]][i + 1]
    fileName = (tableName + ".csv")
    ro.globalenv['fileName'] = fileName
    last_url = "/n3/all/n6/in%20n3%2028"
    url = (tableUrl + last_url)
    ro.globalenv['url'] = url
    ro.r('table= get_sidra(api= url)')
    ro.r('write.csv(table, file= fileName, row.names = F)')

在 R 中,我可以得到 CSV 奇数行和偶数行:table_NameUrl[[1]][i]table_NameUrl[[1]][i + 1]

但在 Python [[1]][i][[1]][i + 1] 中它不起作用。

错误是:

"None of [Int64Index([1], dtype='int64')] are in the [columns]"

CSV 的短版:

帕努 2.1.1、2.1.5

/t/2093/p/2000,2010/v/93/c86/2776,2777,2778,2779,2780,2781/c2/0,4,5/c1/1,2/

帕努 5.1.1、5.1.2、5.1.3、5.1.4、5.1.5、5.1.6、5.1.7、5.1.9、5.1.10

/t/1612/p/2013,2014,2015,2016,2017/v/109,216,214/c81/2688,2691,2692,2694,2696,2708,2702,2715,2703/

帕努 5.1.8

/t/839/p/2013,2014,2015,2016,2017/v/109,216,214/c81/114254/

在R中,tableName = table_NameUrl[[1]][i]的输出是表名,例如:

Panu 2.1.1, 2.1.5

tableUrl = table_NameUrl[[1]][i + 1] 的输出是 url,例如: /t/2093/p/2000,2010/v/93/c86/2776,2777,2778,2779,2780,2781/c2/0,4,5/c1/1,2/

谁能帮我转换一下这个函数?

提前致谢!

【问题讨论】:

    标签: python r


    【解决方案1】:

    根据docs,您可以使用iloc 函数来选择数据框中的行:

    import pandas as pd 
    
    table_NameUrl = pd.read_csv("Data.txt", sep=";", header= None)
    even_rows = table_NameUrl.iloc[::2]
    odd_rows = table_NameUrl.iloc[1::2]
    

    even_rows = table_NameUrl.iloc[lambda x: x.index % 2 == 0]
    odd_rows = table_NameUrl.iloc[lambda x: x.index % 2 == 1]
    

    【讨论】:

      【解决方案2】:

      您可以使用这两个函数来获取数据帧的偶数行或奇数行:

      def get_even_rows(dataframe):
          return dataframe[[i % 2 == 0 for i in range(df.shape[0])]]
      
      
      def get_odd_rows(dataframe):
          return dataframe[[i % 2 != 0 for i in range(df.shape[0])]]
      

      【讨论】:

        猜你喜欢
        • 2020-07-20
        • 1970-01-01
        • 2020-06-24
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多