Python Pandas read_csv保持列顺序

时间:2015-06-30 05:29:01

标签: python pandas

我正在将一个CSV文件读入pandas:

df = pd.read_csv('file.csv')

但是,我注意到不保留列顺序。我无法在文档中找到任何解释如何在读取CSV文件时保持列顺序的内容。

2 个答案:

答案 0 :(得分:0)

read.csv将表格数据转换为DataFrame对象。由于DataFramekwargs字典,因此订单不会受到影响。

来自DataFrameread.csv

的来源

答案 1 :(得分:0)

您可以按照您希望的顺序传递列的列表:

# Returns the sum of num1 and num2
def add(num1, num2):
    return num1 + num2

# returns the results of subtracting num1 - num2
def sub(num1, num2):
    return num1 - num2

# returns the result of multiplying num1 * num2
def mul(num1, num2):
    return num1 * num2

# returns the result of dividing num1/num2
def div(num1, num2):
    try:
        return num1 / num2
    except ZeroDivisionError:
        print("handled div by zero. Returning zero.")
    return 0

def main():
    validInput = False
    while not validInput:
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide. Enter number:"))
            validInput = True
        except:
            print("invalid input. Try again")
    if (operation == 1):
        print("Adding...")
        print(add(num1, num2))
    elif (operation == 2):
        print("Subtracting...")
        print(sub(num1, num2))
    elif (operation == 3):
        print("Multiplying...")
        print(mul(num1, num2))
    elif (operation == 4):
        print("Dividing...")
        print(div(num1, num2))
    else:
        print("I don't understand")

main()