Reputation: 423
#df
index a b c
1 2 3 4
2 3 4 5
df[["a","c"]] # But index no. is also coming, so how to remove the index no.?
Upvotes: 12
Views: 41014
Reputation: 769
This might work for your case:
# import pandas package as pd
import pandas as pd
# Define a dictionary containing students data
data = {'a': [2, 3],
'b': [3, 4],
'c': [4, 5]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data, columns=['a', 'b','c'])
print("Given Dataframe :\n", df)
print("\nIterating over rows using iloc function :\n")
# iterate through each row and select
# 0th and 2nd index column respectively.
for i in range(len(df)):
print(df.iloc[i, 0], df.iloc[i, 2])
Output:
Given Dataframe :
a b c
0 2 3 4
1 3 4 5
Iterating over rows using iloc function :
2 4
3 5
Tested here:
https://onecompiler.com/python/3zht3ravp
Solution source -
Method 3: Using iloc[] function of the DataFrame. :
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
Upvotes: 0
Reputation: 1
The simple answer to achieve what the OP was specifically asking for is to add the index parameter as follows. e.g.
df[["b","c"]].to_csv("C:\\Desktop\\File.csv",index=False)
Upvotes: 0
Reputation: 17322
DataFrames and Series will always have an index, you can use:
df[["a","c"]].values
output:
array([[2, 4],
[3, 5]], dtype=int64)
Upvotes: 13