10
#df

index  a   b   c
1      2   3   4
2      3   4   5

Please help me how to extract columns "a" and "c" with all the rows but without the index column.

df[["a","c"]] # But index no. is also coming, so how to remove the index no.?

Goutam
  • 377
  • 1
  • 2
  • 11

3 Answers3

10

DataFrames and Series will always have an index, you can use:

df[["a","c"]].values

output:

array([[2, 4],
       [3, 5]], dtype=int64)
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • I wnat to export the file in csv, my code is: df[["b","c"]].to_csv("C:\\Desktop\\File.csv") ; but still unable remove the Index column. – Goutam Apr 17 '20 at 14:52
  • this is correct. But it is not completely solved my issue. Let me know if you have any solution for this. – Goutam Apr 17 '20 at 14:57
  • @Goutam to save to a CSV you can use:`numpy.savetxt("foo.csv", a, delimiter=",")` where `a = df[["a","c"]].values` – kederrac Apr 17 '20 at 14:59
  • you can have a look over https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file – kederrac Apr 17 '20 at 14:59
0

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)
Jonathan Ciapetti
  • 1,261
  • 3
  • 11
  • 16
Cobe
  • 1
  • 1
0

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/

Lod
  • 657
  • 1
  • 9
  • 30
  • Also this reference for the slice operator explanation: `[row_start:row_end , column_start, column_end] where, row_start refers start row with 0 position as index row_end refers last row with n th position as index column_start refers start column with 0 position as index column_end refers last column with n th position as index` https://www.geeksforgeeks.org/how-to-get-first-column-of-pandas-dataframe/ – Lod Aug 17 '23 at 11:58
  • Other methods here as well https://www.youtube.com/watch?v=mT-2AxZLtvw – Lod Aug 17 '23 at 13:35